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
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#!/bin/bash

BASEDIR=/home/projects # SET THIS
BAKDIR=/home/backups # SET THIS

stamp=$(date +%Y-%m-%d)

cd "$BASEDIR"
for prj in * ; do

find "$prj" -mtime -1 -type f | grep "" >/dev/null && {
        tar cjf "$BAKDIR/${prj}_${stamp}.tar.bz2" "$prj"
        find "$BAKDIR" -name "${prj}_*" -mtime -14 -mtime +7 -not -name "*-01.*" -exec rm {} \;
        ls -sh "$BAKDIR/${prj}_"*
}

done

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