Skip to content

Instantly share code, notes, and snippets.

@miaucl
Last active February 27, 2021 14:28
Show Gist options
  • Save miaucl/09ef5b65d86384805817a3d0375de8ad to your computer and use it in GitHub Desktop.
Save miaucl/09ef5b65d86384805817a3d0375de8ad to your computer and use it in GitHub Desktop.
Raspberry Pi Backups on External Device

Mount

  1. Mount the external device automatically, here it is a NAS available at the address/path //CL-NAS/home mounted to /backup. Add following line to /etc/fstab:
//CL-NAS/home         /backup       cifs  defaults,rw,credentials=/etc/nas-credentials,x-systemd.automount 0 0

To mount a usb device instead, have a look at this

This will keep the external device mounted at the specified location, even after reboots and crashes.

  1. Add a credential file at /etc/nas-credentials:
username=****
password=****
  1. Add the backup script to perform and manage the backups. As a standard, at most the last 5 backups are kept before deleting them. This can be changed in the script. Look at file backup.sh for more information.

  2. Add a cron job to execute the backup script periodically.

To edit the cron tab:

sudo crontab -e

Add following line:

0 1 * * 0 /backup/backup.sh >> /var/log/cron.log 2>&1

And now you should have automatic backups of your Raspberry Pi!

#!/bin/bash
# VARIABLES - Edit here
BACKUP_PATH="/backup" # Define the path where to store the backup
BACKUP_MAX_COUNT="5" # Set the max number of backups to store
BACKUP_NAME="MyRaspberryPiBackup" # Give the backup a name
SERVICES_START_STOP="service ..." # All services which should be stopped/started during the backup
# Stops the services before the backup
#${SERVICES_START_STOP} stop
# Backup using dd and save to path
dd if=/dev/mmcblk0 of=${BACKUP_PATH}/${BACKUP_NAME}-$(date +%Y%m%d-%H%M%S).img bs=1MB
# Starts the services after the backup
#${SERVICES_START_STOP} start
# Remoe old backups after X new backups
pushd ${BACKUP_PATH}; ls -tr ${BACKUP_PATH}/${BACKUP_NAME}* | head -n -${BACKUP_MAX_COUNT} | xargs rm; popd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment