Backup Pi Image
Purpose
I use this to backup my Raspberry Pi SD card to my Linux computer every 1st and 15th of the month.
This script when run for the first time will create a full disk image of the SD card from which the Pi is running. This image will not contain empty space and thus will be smaller than the full size of the SD card.
On subsequent runs the script will add to the existing image any changes made in the Pi SD card. In other words the script modifies the existing backup image file.
Requirements
- A Raspberry Pi running Buster or Bullseye.
- Another computer with ssh setup.
- The Pi and the computer connected by LAN or WLAN.
- The Pi user should be able to ssh into the computer using key based authentication.
In the Pi:
We will use sshfs
to mount the remote folder in the computer in the Raspberry Pi, so that the SD card image can be written directly in the remote folder. Install sshfs
with the command:
sudo apt install sshfs
Download RonR-RPi-image-utils-master zip file from
Either: the GitHub repo
Or: the Raspberry Pi Forum Post
Unzip the image-utils.zip
file in ~/bin/image-utils/
sudo mkdir /mnt/backup
sudo chmod 777 /mnt/backup
Create ~/bin/pibackup.sh
as:
#!/bin/bash
# /home/username1/bin/pibackup.sh
# By: user68186
# Date: Jan 24, 2022
# Purpose: Backup the whole SD card running Pi to the computer
# Requires sshfs, RomR's image-utils: https://github.com/seamusdemora/RonR-RPi-image-utils
/usr/bin/sshfs username2@computer.local:/path/to/PiDiskImage /mnt/backup
/home/username1/bin/image-utils/image-backup /mnt/backup/mybullseye.img
/usr/bin/sleep 10
/usr/bin/umount /mnt/backup
Make the following changes to the above script:
- Replace
username1
with the username of the Pi user.
- Replace
username2
with the username of the computer user.
- Replace
/path/to/PiDiskImage
to the actual folder in the computer where the image will be saved.
- Replace
mybullseye.img
with the file name of your choice.
Run the script to see if it works and create the initial image backup.
sudo ~/bin/pibackup.sh
If all goes well you will have an image file, /path/to/PiDiskImage/mybullseye.img
Finally automate the backup process
Add in root’s crontab using the command:
sudo crontab -e
the following line:
0 23 1,15 * * /home/username/bin/pibackup.sh
This will run as root on 1st and 15th of each month at 11 PM.
In the Computer
Create a folder PiDiskImage
where you will be keeping the Pi SD card image backup.
mkdir /path/to/PiDiskImage
Make sure the computer has sufficient disk space to keep at least one copy of the Pi disk image.
If you want a fresh full backup for some reason, rename the file mybullseye.img
in the computer to something else. A new mybullseye.img
will be created on the next run.
Hope this helps