Incremental server backup with rsync

Published 05 June 2012 under server, backup

We have a VPS on which we keep our web server and project code. This stuff is important for our business so we back it up daily onto a machine in our office. Here's a really simple and easy way to backup the /home partition from a remote server.

Using ideas from here the following script keeps incremental backups for the past 3 days. daily.2 contains the backup from 2 days ago, daily.3 from 3 days ago etc.

#!/bin/bash

# do-backup.sh

# Directory in which to store the backups
ROOT_DIR=/path/to/backup/dir
REMOTE_USER=myremoteuser
REMOVE_SERVER=myremoteserverip

# step 1: delete oldest snapshot
if [ -d $ROOT_DIR/daily.3 ]; then
    rm -rf $ROOT_DIR/daily.3
fi

# step 2: shift middle backups back by one if they exist
if [ -d $ROOT_DIR/daily.2 ]; then
    mv $ROOT_DIR/daily.2 $ROOT_DIR/daily.3
fi
if [ -d $ROOT_DIR/daily.1 ]; then
    mv $ROOT_DIR/daily.1 $ROOT_DIR/daily.2
fi
# step 3: make a hardlink copy of the latest backup
if [ -d $ROOT_DIR/daily.0 ]; then
    cp -al $ROOT_DIR/daily.0 $ROOT_DIR/daily.1
fi

# step 4: rsync from the system into the latest snapshot (notice that
# rsync behaves like cp --remove-destination by default, so the destination
# is unlinked first.  If it were not so, this would copy over the other
# snapshot(s) too!
rsync -av --delete $REMOTE_USER@$REMOTE_SERVER:/home $ROOT_DIR/daily.0

# step 5: update the mtime of daily.0 to reflect the snapshot time
touch $ROOT_DIR/daily.0

We run the script in a cronjob every day:

@daily /path/to/backup/dir/do-backup.sh > /path/to/backup/dir/do-backup.log

Comments

blog comments powered by Disqus