How to backup a Raspberry Pi and restore it on a smaller SD card

If you’re using Raspberry Pi, you might know the famous command line utility dd, useful to write a Raspbian image to a blank SD card (cf. http://elinux.org/RPi_Easy_SD_Card_Setup).

You can also use this tool to do backup of the whole disk, but it has two drawbacks :

  1. when you copy the whole disk, the image is as big as the disk, even if the is lots of empty space on it.
  2. when you restore the backup you need a disk at least as big as the original one.

Those two disadvantages lead me to find a solution to make backups smaller and more versatile. The solution I’ll describe here is an adaptation of Ubuntu’s documentation : https://help.ubuntu.com/community/BackupYourSystem/TAR and have been tested on Ubutnu 14.04.

To backup, make a tarball of all the files on the partitions :
cd /path/to/sdcard/partition && sudo tar -cpzf /path/to/backup.tar.gz --one-file-system .

As there are 2 partitions on Raspberry Pi’s sdcard : the first is FAT32 and small (around 60MB) and the second is ext4

You should make two backups. Forme its :

cd /media/boot && sudo tar -cpzf /home/antoine/boot.tar.gz --one-file-system .
cd /media/system && sudo tar -cpzf /home/antoine/system.tar.gz --one-file-system .

My sdcard is 16Go while my backup is less than 600Mo !

To restore this backup on a new sdcard, you first have to format it. Make 2 partitions, first FAT32 and 60MB, the second ext4 and big enough to receive all the backup datas. Then extract the 2 archivess to the new 2 partitions with this command :
sudo tar -xvpzf /path/to/boot.tar.gz -C /path/to/sdcard/partition/boot/ --numeric-owner

That’s it !

One drawback is that method works only on system that can mount ext4 something that Windows and Mac OSX can’t do natively…