Linux – How to Automate Borg Backup?

backupbashcronlinuxshell

Background

I would like to use Borg Backup as a backup solution for my Ubuntu server. They offer a very convenient sh script that they say you can just run as a cron job, but it is not working for me.

Problem

How do I automate borg backup? If the best way is to use cron, then what is wrong with my impementation?

Data

Root's Crontab:

# 5 2 * * * sh /home/***/Scripts/borgBackup_run.sh >/dev/null      # Back up the root partition daily (2:05a)
* * * * * sh /home/***/Scripts/borgBackup_run.sh >/dev/null      # Test the script

borgBackup_run.sh:

Modified from the original to be very bare-bones:

#!/bin/sh

echo 'Starting backup now...' >> 
/home/***/Logs/borgBackup_create.log

#/usr/bin/borg create --verbose --filter AME --list --stats --show-rc --compression lz4 --exclude-caches --one-file-system --exclude-from ~/Scripts/borgBackup_exclude.txt /mnt/RootBackup/borg::'{hostname}-{now:%Y-%m-%d}' /
/usr/bin/borg create /mnt/RootBackup/borg::cronTest /home/***/Logs/ # Backup a small folder as a test

echo 'Done.' >> /home/***/Logs/borgBackup_create.log

"ls -l ~/Scripts/borgBackup_run.sh"

-rwxr-xr-x 1 root root 455 Sep 27 12:34 Scripts/borgBackup_run.sh

Notes:

When borgBackup_run.sh is run from the commandline, as: sudo Scripts/borgBackup_run.sh, the script works perfectly, creating a new archive in /mnt/RootBackup/borg.

Additionally, after each minute (when the cronjob runs), the .log file at /home/***/Logs/borgBackup_create.log shows both Starting backup now... and Done., indicating that the script has run all the way through, but borg did not work for some reason.

I have tried removing sh from the crontab file, using bash instead, and changing the interobang to #!/bin/bash instead of #!/bin/sh. I have also tried wrapping the line /user/bin/borg create ... line in borgBackup_run.sh in bash -c "...".

Any help would be greatly appreciated!

Best Answer

I figured out the problem, and am posting the solution in case anyone in the future has a similar problem.

I set up my repository to be unencrypted, which caused borg to attempt to run interactively (asking stdout if backing up to an unencrypted repository is ok). To make borg run non-interactively, I had to export an "automatic answerer" in borgBackup_run.sh, before the call to borg create .... The new line in the script looks like:

export BORG_UNKNOWN_UNENCRYPTED_REPO_ACCESS_IS_OK=yes

The name of this variable was found in the man page for borg. A number of other "automatic answerers" can also be found in the man page, to ensure that borg runs non-interactively in a script.