Backing up the SD card in your Raspberry Pi takes a lot of time: shutting down the Raspberry Pi, removing the SD card, inserting it into your computer, creating an image of the SD card, reinserting it into the Raspberry Pi, switching the Raspberry Pi back on… in short, a lot of manual work and downtime for the whole duration of the backup. You can also back up with the application now built into the Raspbian GUI (SD Card Copier), which lets you clone the SD card to an external disk without any downtime, but it still requires physical access to the device to connect an external disk to one of the Raspberry Pi’s USB ports. But what if you want to create a backup image of your SD card over SSH? Here is a short guide to doing this conveniently. These instructions for creating and restoring the backup work on all Linux systems.
Creating the backup file
Open a terminal session and run the following command, replacing the parts in red (the Raspberry Pi’s IP address and the backup file name):
ssh pi@192.168.0.101 “sudo dd if=/dev/mmcblk0 bs=1M status=progress | gzip -” | dd of=~/Desktop/backup_2020-12-08.gz
As soon as you run the command, the system will ask for the password for the “pi” user. Enter it and wait for the backup to complete.
If you are using a Mac, you can check the current status of the backup by pressing “CTRL” + “T“. You can press this repeatedly during the backup to see how many bytes have been transferred.
When the backup is complete, the input prompt will reappear in the terminal.
Restoring the backup
Restoring the backup does not work remotely. After all, the system would be overwritten while running, which would be exactly like sawing off the branch you are sitting on. If it were possible, it would be a major security risk. In this case you have to intervene physically, removing the SD card from the Raspberry Pi and restoring the backup to it.
Open a terminal session and run the following command, again changing the parts in red (the destination disk {SD card} and the backup file name):
diskutil unmountDisk /dev/disk1
gzip -dc ~/Desktop/backup_2020-12-08.gz | sudo dd of=/dev/rdisk1 bs=1m conv=noerror,sync
Enjoy!
