Time Machine alternative for linux: automate your backups

Introduction

MacOS has a good backup system which allows you to recover any files that have beed deleted or to restore previous versions of the files. I works like you can literally come back into a certain moment back in time.

Now that I have set up Raspberry Pi based home NAS, I found a solution that achieves the same results on linux: incrental backups with rsync.

Instruction: how to automate backups on Linux

Step 1. Set up rsync backup script, with instructions and settings on how to run the backup

sudo mkdir /usr/local/scripts    //make folder to store scripts
sudo nano /usr/local/scripts/rsync_backup.sh  //create the script:
# This script makes backups from DATA location to BACKUP location and puts in date-named folders corresponding to date of each backup

# BACKUP SETTINGS, configure data and backup location:
DATA=/media/data_dir      #this folder is backed up
BACKUP=/media/backup_dir/backup_name  #to this folder

# SCRIPT BODY, no need to make changres unless you want to tweak it:
THIS_BACKUP_PATH=${BACKUP}/$(date +%Y-%m-%d) # today's date
LAST_BACKUP_PATH=${BACKUP}/$(ls ${BACKUP} | tail -n 1)
mkdir -p ${THIS_BACKUP_PATH}

rsync -av --link-dest ${LAST_BACKUP_PATH} ${DATA} ${THIS_BACKUP_PATH} $@
sudo chmod +x  /scripts/rsync_backup.sh  //add execute permission

Step 2. Set up cron job to run the backup script on a schedule

sudo crontab -e

To run your backup script at 3am every night, add this to your cron file:

0 3 * * *  /usr/local/scripts/rsync_backup.sh
# Other options
0 3 1 * *  /path/to/schipt.sh   # run every month at 3am

The syntax works like this (you can mofy it according to your needs):

* * * * * command to be executed
- - - - -
| | | | |
| | | | ----- Day of week (0 - 7) (Sunday=0 or 7)
| | | ------- Month (1 - 12)
| | --------- Day of month (1 - 31)
| ----------- Hour (0 - 23)
------------- Minute (0 - 59)

Useful Links

More on cron read here, or crontab calculator here

Bash scripts 101