Quick Restic Tip: Backup when suspending laptop with systemd

I love restic. It’s easy, fast and reliable with a ton of nice features and well documented. If you need to restore a backup it’s probably very stressful. Therefor it’s important to do backups regularly.

Through the day there’s often not a good time to backup your data. One saturday evening  I was thinking about it and an idea popped into my head: Every evening I suspend the laptop. Maybe I can intercept that and perform my backup before sending my laptop into standby?

Yes – you can run scripts before the system suspends easily with systemd!

Just place your script in /usr/lib/systemd/system-sleep/ and ensure it’s executable.

#!/bin/bash
if [ "${1}" == "pre" ]; 
then
  # Execute your backup script
  /bin/backup
elif [ "${1}" == "post" ]; then
	exit 0
fi

For easier mounting I added a partition label to the external disk:

e2label /dev/sdb1 external_backup

Now we can check in our backup script /bin/backup  – be sure to place it on an encrypted partition. If we can mount our external disk by the label continue with the backup. If not abort the script.

#!/bin/bash
mount LABEL="external_backup" /backup/ # mount the external disk labelled with 'external_backup'
retVal=$?
# when mount fails the exit code is not equal 0
if [ $retVal -ne 0 ]; then 
    echo "Cannot mount disk, aborting"
    exit 0
fi
# perform the actual backup script
restic -r /backup/REPO --verbose backup YOUR_DIR_TO_BACKUP --password-file <(echo YOUR_BACKUP_PW)
umount /backup

Kommentare

Vielen Dank für Deinen Kommentar! Dieser muss jetzt nur noch freigegeben werden.

Ich akzeptiere die Kommentarrichtlinien sowie die Datenschutzbestimmungen* *Pflichtfelder