3.3 Periodic Back-ups

The SD card that carries the Pi OS isn't always as reliable as you'd like it to be. Sudden power loss, for example, can corrupt your card to the point where it won't boot your Pi any longer. Combine this with the lack of a power button and you might be tempted to just unplug your Pi when moving it about; a recipe for disaster.

Safely shutting down the Pi

If you need to unplug the Pi, make sure to call the following command before doing so:

sudo halt

This will shutdown the Pi and make sure no write operations will be interrupted.

Backing up the entire SD card to external storage

The following is from this post. It will the entire SD card to an image stored on the external storage. Of course, you should make sure you have at least enough space available on the external storage before doing this.

To quote the words of caution:

Caution - be careful using the dd command, make sure you get the right syntax, particularily the if and of options, get them the wrong way round and your gonna need the backup you haven't taken!

The following command stores the image in the root of the external drive and assumes it is mounted on `/media/hdd/' (as described in 3.2), you might have chosen yours differently.

sudo dd if=/dev/mmcblk0 of=/media/hdd/

Performance note: NTFS vs ext4

Beware: on my Pi, this took 8757.16 seconds for a 16Gb SD card. Yup, that's 2 and a half hours. Big factor here was the use of NTFS on the external drive. I haven't done a benchmark but once I reformatted a drive to ext4 I noticed an 5-10 fold increase in write performance.

Periodic, automatic backups using Cron

Crob jobs are Linux' way to automatically execute tasks at certain intervals. To add a cron job: crontab -e will open the cron file in an editor. Extensive and comprehensible docs about the cron file format can be found here, but it basically boils down to this:

* * * * * command to be executed
- - - - -
| | | | |
| | | | ------ Day of week (0 - 7) (Sunday=0 or 7)
| | | ------- Month (1 - 12)
| | --------- Day of month (1 - 31)
| ----------- Hour (0 - 23)
------------- Minute (0 - 59)

Where each * can be a number, a range (1-5), comma separated values (1,14,16) or an asterisk.

To automatically back-up your SD card every week on a Sunday night at 2:00 am, you'd add something like this to the cron file:

0 2 * * 0   sudo dd if=/dev/mmcblk0 of=/media/hdd/

You can also write a more elaborate script that takes into account stopping running services before the backup and restarting them afterwards, or that keeps the last 10 backups and deletes older ones. This script could be a good base for yours.

At last, a few useful commands when using cron jobs:

  • Edit cron jobs: crontab -e
  • View all cron jobs: crontab -l
  • View cron jobs for a user: crontab -u username -l

results matching ""

    No results matching ""