Rotating Folder Backup Script

How do you create folder backup archives and limit the size by rotating old ones out? A common task and there are plenty of solutions. This is more or less the poor man's solution I'm running from cron.

This script will process each sub folder of a given base directory. If there are modified files it will create a archive tar and possibly clean out old ones. The last 7-days of snapshots and each 1st of the month will be kept.

  1. #!/bin/bash
  2.  
  3. BASEDIR=/home/projects # SET THIS
  4. BAKDIR=/home/backups # SET THIS
  5.  
  6. stamp=$(date +%Y-%m-%d)
  7.  
  8. cd "$BASEDIR"
  9. for prj in * ; do
  10.  
  11. find "$prj" -mtime -1 -type f | grep "" >/dev/null && {
  12. tar cjf "$BAKDIR/${prj}_${stamp}.tar.bz2" "$prj"
  13. find "$BAKDIR" -name "${prj}_*" -mtime -14 -mtime +7 -not -name "*-01.*" -exec rm {} \;
  14. ls -sh "$BAKDIR/${prj}_"*
  15. }
  16.  
  17. done

The script needs the bash shell and works with whitespace in directory- and filenames.

Comments

Role of prj and for loop

the for do loop enumerates all sub-folders in the BASEDIR (I have one folder for each project, thus prj). Each project is archived on it’s own. You can throw that away if you are just looking to archive a single folder.

prj

Hi Zany,
Can you explain what 'prj' means?

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • You can use BBCode tags in the text.
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. Beside the tag style "<foo>" it is also possible to use "[foo]".

More information about formatting options