Backups using bup

on under Snippets

After a little accident concerning my hard drive, I decided that it probably would be a good idea to do backups more regularly. After some recommendations and a little bit of reading, bup seemed to be the way to go. It is a nice git based backup tool, allowing incremental backups with deduplication. For storage I use an encrypted external hard drive.

To streamline the regular backup process as bit, I use this small bash script:

#!/bin/bash
set -e

if [[ $EUID -ne 0 ]]; then
	echo "This script must be run as root" 1>&2
	exit 1
fi

PARTUUID=<insert partition UUID here>
EXCLUDED='--exclude=/tmp --exclude=/dev --exclude=/mnt --exclude=/media --exclude=/proc --exclude=/sys'
BACKUP_DIR_ROOT="/"
BACKUP_DIR_HOME="/home"
MAPPER_PATH="/dev/mapper/cryptbackup"
export BUP_DIR="/mnt/backup_external/backup"

if [ ! -e $MAPPER_PATH  ]; then
	cryptsetup luksOpen -d <insert path to keyfile here> /dev/disk/by-partuuid/$PARTUUID cryptbackup
fi

if [ ! -e $BUP_DIR  ]; then
	echo "==== Mounting Backup Disk ===="
	mount -o sync $MAPPER_PATH /mnt/backup_external
	mounted=true
fi

echo "==== Indexing root ===="
eval bup index $EXCLUDED -f $BUP_DIR/balthasar-root-index -xu $BACKUP_DIR_ROOT
echo "==== Saving  root ===="
eval bup save -f $BUP_DIR/balthasar-root-index -n balthasar-root $BACKUP_DIR_ROOT
echo "==== Indexing home ===="
eval bup index $EXCLUDED -f $BUP_DIR/balthasar-home-index -xu $BACKUP_DIR_HOME
echo "==== Saving home ===="
eval bup save -f $BUP_DIR/balthasar-home-index -n balthasar-home $BACKUP_DIR_HOME
echo "==== Generating redundancy ===="
bup fsck -gv -j5 | grep generated

date +"@%s" > "/home/ravinrabbid/.lastbackup"

if [ $mounted ]; then
	echo "==== Unmounting Backup Disk ===="
	umount /dev/mapper/cryptbackup
	cryptsetup luksClose $MAPPER_PATH
fi

echo "==== Backup successful ===="

Mind, that I use different bup repos for my home and root file systems. Both have to be already initialized. To be able to access the whole root file system, the script has to be run with according permissions.

The excluded directories should not be necessary, since the -x flag prevents crossing of file system borders during indexing, but I also use the variable for some cache directories within my home. The script also generates recovery information to rescue corrupted backups (You should really do this, I already had to use it!)

Finally you may wonder, what the data command does. It simply stores the timestamp of the last successful backup. I use this for an indicator in my i3bar to remind me that it’s time to update my backups.

bash, backup, linux