Skip to content

Instantly share code, notes, and snippets.

@heywoodlh
Last active October 6, 2020 18:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heywoodlh/4632e3320353b30bd57166a70c2a0eaa to your computer and use it in GitHub Desktop.
Save heywoodlh/4632e3320353b30bd57166a70c2a0eaa to your computer and use it in GitHub Desktop.
Tarsnap backup script
#!/usr/bin/env bash
## This script assumes that ssmtp is already configured on the server.
KEYFILE="/tmp/tarsnap.key"
EMAIL="joe@myemail.com"
BACKUP_NAME="$(uname -n)-server-backup-$(date +%Y-%m-%d_%H-%M-%S)"
DATA_PATH="/tmp/path1 /tmp/path2"
TOTAL_BACKUPS='3'
EXCLUDE="" #space separated paths if you need multiple exclusions
CACHE_DIR="/usr/local/tarsnap-cache"
## DO NOT EDIT BELOW THIS LINE##
DATE="$(date +%b-%d-%y)"
echo "Backup: $BACKUP_NAME"
TARSNAP="$(which tarsnap)"
EXCLUDE_ARG=""
if [[ "$EXCLUDE" != "" ]]
then
for file in $EXCLUDE
do
EXCLUDE_ARG="$EXCLUDE_ARG--exclude $file "
done
fi
# Create the backup
$TARSNAP -c $EXCLUDE_ARG --keyfile $KEYFILE --cachedir $CACHE_DIR -f $BACKUP_NAME $DATA_PATH
BACKUP_STATUS="$?"
ARCHIVE_NUMBER="$($TARSNAP --keyfile $KEYFILE --cachedir $CACHE_DIR --list-archives | sort | wc -l)"
##Limit of three stored backups. If limit is reached, delete the oldest backup
if [ "$ARCHIVE_NUMBER" -gt "$TOTAL_BACKUPS" ]
then
OFFENDING_BACKUP="$($TARSNAP --keyfile $KEYFILE --cachedir $CACHE_DIR --list-archives | sort | head -1)"
$TARSNAP -d --keyfile $KEYFILE --cachedir $CACHE_DIR -f "$OFFENDING_BACKUP"
fi
CURRENT_ARCHIVE="$($TARSNAP --keyfile $KEYFILE --cachedir $CACHE_DIR --list-archives | sort)"
if [ "$BACKUP_STATUS" == "0" ]
then
echo "Backup complete"
echo "Tarsnap backup completed: $DATE. Current backups: $CURRENT_ARCHIVE" | ssmtp "$EMAIL"
else
echo "Backup failed"
echo "Tarsnap backup failed: $DATE". | ssmtp "$EMAIL"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment