Blair’s Science Desk

25. Borg backups

· Blair Fix

I haven’t posted here in a while! Today, I thought I’d get back in the habit by posting my Borg backup script. Borg is a command-line backup app written in Python. It’s blazing fast and features great de-duplication.

To get started with Borg, follow the installation instructions here.

Then, initialize a backup with this command:

borg init  /path/to/backup 

Here’s my backup script. First we make a backup of my /home directory:

# backup
# --------------------------------------------

borg create                         \
    --verbose                       \
    --filter AME                    \
    --list                          \
    --stats                         \
    --show-rc                       \
    --compression lz4               \
    --exclude-caches                \
    --exclude 'home/blair/Downloads/*'     \
    --exclude 'home/blair/torrents/*'     \
    /media/blair/Backup_drive/backups/borg_blair::'{hostname}-{now}' \
    /home/

I run this script every hour (with a cronjob). Of course, I don’t want to keep all the hourly backups. So I prune the archive to keep 24 hourly backups, 14 daily backups, 8 weekly backups, and 6 monthly backups. Here’s the code:

# prune
# --------------------------------------------

borg prune                          \
    --list                          \
    --glob-archives '{hostname}-*'  \
    --show-rc                       \
    --keep-hourly   24		    \
    --keep-daily    14              \
    --keep-weekly   8               \
    --keep-monthly  6		    \
    /media/blair/Backup_drive/backups/borg_blair


prune_exit=$?

The we compact the archive:


# compact
# --------------------------------------------

echo "Compacting repository"
borg compact /media/blair/Backup_drive/backups/borg_blair
compact_exit=$?

Finally, we check for errors.


# check for errors
# --------------------------------------------

global_exit=$(( backup_exit > prune_exit ? backup_exit : prune_exit ))
global_exit=$(( compact_exit > global_exit ? compact_exit : global_exit ))

if [ ${global_exit} -eq 0 ]; then
    echo "Backup, Prune, and Compact finished successfully"
elif [ ${global_exit} -eq 1 ]; then
    echo "Backup, Prune, and/or Compact finished with warnings"
else
    echo "Backup, Prune, and/or Compact finished with errors"
fi

exit ${global_exit}

I use this code to backup my main computer. And via WSL, I also use it to backup my wife’s Windows machine.