How to Backup and Clone Raspberry Pi SD Card Automatically
Making automatic backups of your Raspberry Pi SD Card is a good practice considering the lifespan of an SD Card. Eventually the SD Card is going to give out, and you will run into read/write issues.
Let's explore how to automatically create live backups of your Raspberry Pi SD Card.
Step 1: Setup & Installation
We are going to be using a tool called rpi-clone found on Github.
First, let's clone the repository and make a copy of the rpi-clone shell script so we can access the program by name.
$git clone https://github.com/billw2/rpi-clone.git
$cd rpi-clone/
$sudo cp rpi-clone /usr/local/sbin/rpi-clone
Now that we have the program installed, let's explore how to make a backup.
Step 2: Create Backup
We need to find the name of the device that will be backed up to.
$lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
sda 8:0 1 29.7G 0 disk
└─sda1 8:1 1 29.7G 0 part
mmcblk0 179:0 0 29.7G 0 disk
├─mmcblk0p1 179:1 0 256M 0 part /boot
└─mmcblk0p2 179:2 0 29.5G 0 part /
I'm using a USB SD Card Reader with a MicroSD Card inserted into it, which will serve as the backup card in the event that the main MicroSD Card fails.
The name of the disk may be different, so make sure that you are referencing the correct drive so that you don't accidentally overwrite something you weren't intending to.
In my case, the name of the disk I will backup to is sda.
Everything is setup and we have the name of the disk we will be backing up to, so let's now run the program to make sure that everything backs up correctly.
$sudo rpi-clone sda
After issuing the command, press [enter] to move through the prompts until the program runs.
This process can take a while, so it would be a perfect opportunity to stand up and stretch or find yourself a nice glass of water.
Step 3: Automate Backups
Automatically creating a backup can be done through creating a cron job, so let's create a job entry.
$sudo crontab -e
This will open a file that contains entries for scheduling cron jobs. We will create an entry to run the backup daily at midnight.
Scroll to the bottom of the file and add the cron job entry, replacing sda with the name of your drive.
We also need to tack on the -q parameter which will tell the program to run unattended and quietly.
# m h dom mon dow command
@daily rpi-clone sda -q
Save the file and exit.
Notes
The initial sourcing or the first creation of the backup disk, will take some time to complete as it is copying the entire filesystem.
Any subsequent clones (automatic backups) will perform quicker because only modified files will be backed up. This makes it viable to run the backup automation frequently.