I recently got a Raspberry Pi to play with, so I figured it was a good time to setup automatic local backups for my important files. I wrote this simple Bash script (local-backup.sh) and added it to a cron job running every 30 min.

# Backup source configs
SOURCE_HOME="/Users/yourusernamehere/"
DIRECTORIES=('Desktop' 'Documents' 'Other' 'Scripts')

# Backup destination configs
USER="rpi-username"
HOST="rpi-host"
DESTINATION="/destination/backup/directory/"

ls /tmp/local-backup.lock
if [ $? == 0 ]
then
  echo "Backups cron already running, exiting"
  exit 0
fi
touch /tmp/local-backup.lock

for dir in "${DIRECTORIES[@]}"
do
  echo $SOURCE_HOME$dir
  rsync -aP $SOURCE_HOME$dir $USER@$HOST:$DESTINATION
  if [ $? != 0 ]
  then
    /usr/local/bin/terminal-notifier -title "Backups cron" -message "'$dir' backup failed"
    rm /tmp/local-backup.lock
    exit 1
  fi
done

rm /tmp/local-backup.lock
exit 0

A few things to note:

  • It assumes you are backing up directories found in your Mac OS user directory, defined using ‘SOURCE_HOME’.
  • The directories you want to backup are defined using ‘DIRECTORIES’.
  • terminal-notifier is used to send failure notifications to to the Mac OS Notification Center. You can install this using ‘brew install terminal-notifier’.

I also recommend creating a new user (without sudo rights) on the Raspberry Pi to connect with using rsync. That way you can use a key pair without a password and limit the fallout if the username and key pair are ever compromised.

  • The rpi-host details are defined using .ssh/config (identityfile, port, ip etc etc)

Now you just need to add a cron job to run the script every 30 min. In terminal just run ‘crontab -e’ then add the following line:

*/30 * * * * /Users/yourusernamehere/local-backup.sh > /Users/yourusernamehere/local-backup.log

The cron also outputs the script output to local-backup.log to help with any debugging.

The last step is to allow cron full disk access in the Mac OS ‘Security & Privacy’ settings otherwise the backup script will fail to run due to permission errors. The following page has the steps required to allow full disk access: