Posted on :: Tags: , , , , , , ,

I decided to write a script to back up only recent files. There are solutions based on unison that work periodically for all files, but as I change projects, I need to configure new backups for these projects as well. This is cumbersome and error-prone; it is easy to forget to add new artifacts to backup scripts and lose them in an emergency.

Therefore, I decided that a small Bash script using rsync and find would work better. It monitors my entire home directory and backs up recent files.

The following script does exactly that:

#!/bin/bash

if [ "x$1" = "x" ] ; then
    TARGET=/media/augustus/backup-recent-`hostname`
else
    TARGET=$1
fi

PERIOD=15

mkdir -p $TARGET

# Delete files older than $PERIOD days
find $TARGET -ctime +$PERIOD -print -delete

# Copy files newer than $PERIOD under ~. Ignore files under .hg
for d in ~/*/ ; do
    find $d -path '*/.hg/*' -prune -o -type f -ctime -$PERIOD -print  -exec rsync -aRv {} $TARGET/ \;
done

It checks whether a command-line option is provided as the target; otherwise, it sets a default target. /media/augustus/ is an NFS mount in my case, but you can specify any path.

PERIOD is the number of days that the script considers recent. Currently, it backs up files changed in the last 15 days.

The script deletes older files from the backup. Since I use other solutions for long-term storage, I don’t want to keep them here, especially since this script runs via cron every two hours.

Note that the script only checks directories under the home directory, so files located directly in the home directory are not backed up.

It also skips files under .hg directories. You can add more -prune options to the find command to exclude other irrelevant directories from your backup.