Using rsync to make rotational backups.

There is a feature in rsync that makes snapshots easy. This feature is a simple option called link-dest. What it does is compare the source path you want to copy from that of the original backup path. It then copies any new or changed files from the source to a second defined backup path. Rsync creates hard links to any none changed files/directories under the second defined backup path. This essentially gives you two snapshots of the original source. The really nice thing about this is that the second backup is only as large as the difference between the last time the sync accured. Now it is also easy to create a script that moves these snapshots to a different directory thus giving you as many snapshots as you like. Below is a simple bash script that demonstrates how this can work for a five day rotational backup.

Note: change the path to the RSYNC and BACKUP variables to fit your environment.

#!/bin/bash
#
# This script uses rsync version 3 to make a 5 day backup of /home.
# 
  
RSYNC="/usr/local/bin/rsync"  

SOURCE="/home/"
  
BACKUP="/backups/1-day-ago/"

OPTIONS="-a --delete  --link-dest="/backups/2-days-ago/""
  
# Increment the backups
rm -rf "/backups/5-days-ago"
mv -f "/backups/4-days-ago" "/backups/5-days-ago"
mv -f "/backups/3-days-ago" "/backups/4-days-ago"
mv -f "/backups/2-days-ago" "/backups/3-days-ago"
mv -f "/backups/1-day-ago" "/backups/2-days-ago"
  
# rsync command
$RSYNC $OPTIONS $SOURCE $BACKUP
  
# touch the backup folder to reflect the date
touch /backups/1-day-ago
  
exit 0

Note: If you are using the rsync that ships Mac OS X make sure you add the -E option to copy any extended attributes. I recommend using the official rsync version 3 release and using the -X option instead.

common/5-day-backup.txt · Last modified: 2011/12/28 12:12 by millerdc