Skip to content

Instantly share code, notes, and snippets.

@gregsexton
Last active July 1, 2016 04:45
Show Gist options
  • Save gregsexton/8195599 to your computer and use it in GitHub Desktop.
Save gregsexton/8195599 to your computer and use it in GitHub Desktop.
My rsync-based backup script
#! /bin/zsh
# Backup script written by Greg Sexton
# bomb out on first non-zero exit code
set -e
trap 'echo !!! BACKUP EXITED WITH ERROR STATUS !!!' ERR
DATE=$(date "+%Y-%m-%dT%H:%M:%S")
ROOT=/mnt/backup
BACKUP_PREFIX="bak-"
WIP_PREFIX="inprogress-"
DEST=$ROOT/$BACKUP_PREFIX$DATE
WIPDEST=$ROOT/$WIP_PREFIX$DATE
LATEST=$ROOT/latest
INCLUDES=/etc/backup
EXCLUDES=/etc/backup-excludes
MIN_SPACE=10000000 #10G
MIN_INCREMENTS=14
echo "\n*** Starting backup at $DATE"
# Precondition: there should be something mounted on $ROOT
mount|grep -q $ROOT
echo "There is a mount point at $ROOT"
# Possibly remove the oldest incremental backup
INC_COUNT=$(ls -1d $ROOT/$BACKUP_PREFIX*|wc -l)
echo "There are $INC_COUNT incremental backups on $ROOT"
if [[ $INC_COUNT -gt MIN_INCREMENTS ]]
then
OLDEST_BACKUP=$(find $ROOT -maxdepth 1 -name "$BACKUP_PREFIX*"|sort|head -1)
echo "Removing: $OLDEST_BACKUP"
rm -rf $OLDEST_BACKUP
echo "Successfully removed $OLDEST_BACKUP"
fi
# Check min space threshold. rsync makes it difficult (without
# parsing) to get the exact space requirement. Use this as a simple
# heuristic instead.
if [[ $(df --output=avail $ROOT|sed -e '1d') -lt $MIN_SPACE ]]
then
echo "The backup volume does not meet the minimum free space requirement."
false
fi
# Backup
for source in $(cat $INCLUDES)
do
LINKDEST=""
if [[ -e $LATEST ]]; then; LINKDEST="--link-dest=$LATEST${source%/}"; fi
echo "* Backing up $source to $DEST"
rsync -ax --stats $LINKDEST \
--delete --delete-excluded \
--exclude-from=$EXCLUDES \
${source%/}/ $WIPDEST${source%/}
done
# Ensure everything is flushed
sync
# Bookkeeping
mv -v $WIPDEST $DEST
rm -vf $LATEST
ln -s $DEST $LATEST
echo "*** Successfully finished backup at $(date "+%Y-%m-%dT%H:%M:%S")"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment