In this tutorial we will be backing up our raspberry pi's contents from our home directory to a external hard drive which is attached to the same raspberry pi.
We will be using rsync, so that we only copy incremental data, rather than overwriting the same data over and over again.
Rsync Basics
To demonstrate, I will create a 512MB file and then use rsync to copy it to my external hard drive, then use it again to demonstrate that it only copied it the first time, as the second time it exited immediately as there were no changes made to the file that we are backing up.
Install Rsync
Install rsync with:
$ sudo apt install rsync -y
Create Dummy Data
Create the 512MB file with fallocate
:
$ mkdir /tmp/test
$ fallocate -l 512M /tmp/test/512mb.file
Verify that the file is 512MB:
$ ls -lah | grep file
-rw-r--r-- 1 pi pi 512M Jun 20 13:33 512mb.file
Use Rsync to Backup
My external hard drive is mapped to /disk/3
:
$ df -h
Filesystem Size Used Avail Use% Mounted on
/dev/root 30G 18G 11G 64% /
/dev/sdb1 932G 516G 417G 56% /disk/3
I will be backing up the the 512MB file from /tmp/test/
to /disk/3/backups/rpi-01/tmp/test/
I am using -a
for recursive and -v
for verbose:
$ rsync -av /tmp/test/ /disk/3/backups/rpi-01/tmp/test/
sending incremental file list
./
512mb.file
sent 537,002,128 bytes received 41 bytes 9,504,463.17 bytes/sec
total size is 536,870,915 speedup is 1.00
We can verify that the file is in our target destination:
$ ls /disk/3/backups/rpi-01/tmp/test/
512mb.file
Now if we run that again without making any changes to our source file, you will notice that it don't copy it again:
$ $ rsync -av /tmp/test/ /disk/3/backups/rpi-01/tmp/test/
sending incremental file list
./
sent 112 bytes received 25 bytes 274.00 bytes/sec
total size is 536,870,915 speedup is 3,918,765.80
If we have to make changes in our source directory only the changes will be synced to our target.
Scripting
We can automate our backup with a bash script and crontab.
Let's say we want to backup our home directory every night at 23:30.
Create the shell script in /home/pi/scripts/backups.sh
or anywhere you want:
#!/usr/bin/env bash
rsync -av /home/pi/ /disk/3/backups/rpi-01/home/pi/
Then make the file executable:
$ chmod +x /home/pi/scripts/backups.sh
Then add it to your crontab, crontab -e
:
30 23 * * * /home/pi/scripts/backups.sh
Now your incremental backups will occur every night at 23:30