Backup the Raspberry Pi to an image File
First you need to find out the device name of the SD card and the mount point of the device where you want to save the backup to:
$ lsblk -o NAME,FSTYPE,SIZE,MOUNTPOINT,LABEL,MODEL
The output will be something like this:
NAME FSTYPE SIZE MOUNTPOINT LABEL MODEL
sda 1.8T ST2000DM001-1CH164
└─sda1 ntfs 1.8T /media/USBHDD1 HD2TB
sdb 4.6T ST5000DM000-1FK178
└─sdb1 ntfs 4.6T /media/USBHDD2 HD5TB
mmcblk0 7.4G
├─mmcblk0p1 vfat 256M /boot boot
└─mmcblk0p2 ext4 7.2G / rootfs
The device name for the SD card is where the / and /boot directories are mounted, mmcblk0 in this case. The mount point where I want to saved the backup to is /media/USBHDD2, where I have created a “Backups” directory. To do the backup execute the dd command like this:
$ sudo dd if=/dev/mmcblk0 of=/media/USBHDD2/Backups/RaspberryPi-full-install-2021-07-22.img bs=1M
Parameter “if” indicates the input file, parameter “of” indicates the output file, parameter “bs” indicates the block size.
The file created will be as large as the full size of the SD card, to compress it directly while creating the backup you can pipe the output of “dd” to “gzip”. You can also use the “date” command to create the file with the day’s date:
$ sudo dd if=/dev/mmcblk0 bs=1M | gzip -c - > /media/USBHDD2/Backups/RaspberryPi-full-install-`date +%F`.img.gz
The next step would be having Schedule it in the crontab. Create a shell script named “backup.sh” in your home bin directory with the command, the add it to the crontab. To edit the crontab:
$ crontab -e
Add a line at the bottom of the file to execute the script:
0 1 * * * /home/pi/bin/backup.sh
To view the crontab:
$ crontab -l
Next day you should find a backup file in the /media/USBHDD2/Backups directory:
-rwxrwxrwx 1 root root 2643155996 Jul 28 03:55 RaspberryPi-full-install-2021-07-28.img.gz