Skip to content

Instantly share code, notes, and snippets.

@adewes
Last active Oct 31, 2022
Embed
What would you like to do?
Borg Backup - Shell script to create regular backups (can e.g. be called hourly by cron).

Borg Backup Script

This is a little helper script to regulary back up your data using the Borg backup tool. I wrote this as I was frustrated with Deja-Dup, which does not allow me to exclude directories by pattern, hence I ended up with backups that were very large and took a really long time to create because they contained many directories with non-essential files (e.g. node modules or Python virtual environments). Borg backup is a simple tool that offers everything that Deja-Dup does and is easier to customize.

  • Put the script in your home folder and make it executable.
  • Call it regularly using e.g. cron (put e.g. "0 * * * * [your username] /home/[your username]/make_backup.sh" in your /etc/crontab - this will call the script every hour). Please note that the script will perform its own checking to see if a new backup is necessary, so it doesn't hurt to call it very often. If you would put a specific date in crontab and it would happen that your computer is turned off at that date, crontab would not execute the backup script. By calling the script every hour we make sure that the backups are created regularly.
  • Modify the arguments that you pass to the Borg CLI to customize the directories that you want to back up.

The script will check the modification date of a file called last_backup.txt in your home directory to decide if a new backup should be created (by default once a week). If the file does not exist it will create it, if the backup fails it will erase it.

#!/bin/bash
DATE=`date +%s`
BORG_PASSPHRASE="your-secret-passphrase"
BACKUP_FILE="$HOME/last_backup.txt"
if [ ! -f $BACKUP_FILE ]; then
touch $BACKUP_FILE
MODIFICATION_DATE=10000000
else
MODIFICATION_DATE=`stat -L --format %Y $BACKUP_FILE`
fi
LAST_BACKUP=`expr $DATE - $MODIFICATION_DATE`
LAST_BACKUP_DAYS=`expr $LAST_BACKUP / 60 / 60 / 24`
LAST_BACKUP_HOURS=`expr $LAST_BACKUP / 60 / 60`
echo "$LAST_BACKUP_DAYS days since last backup ($LAST_BACKUP_HOURS hours)"
if [ $LAST_BACKUP_HOURS -ge 24 ]; then
echo "Time for a new backup!"
touch $BACKUP_FILE
BORG_PASSPHRASE=$BORG_PASSPHRASE borg create ~/Dropbox/backups/ubuntu-borg::`date +%Y-%m-%d-%H-%M` ~/projects ~/.ssh ~/Documents --exclude ".*" --exclude "**/venv" --exclude "**/node_modules" --compression zlib || (echo "Backup failed!" && rm $BACKUP_FILE)
else
echo "Backup still good..."
fi
@michaelijah
Copy link

michaelijah commented Apr 17, 2018

Very Nice. Thanks 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment