Automated Snapshot Backups for Linux – Quick and simple

I’m sharing with you today my extremely simple snapshot script, that I run via a cron everyday. Although there may be apps out there that can do this for you, I prefer to opt for simplicity and write something myself.

What is Rsync?

Rsync is an application that allows you to sync directories locally or over networks. It allows for incremental updates to files, meaning that you can save time/bandwidth when making backups. Very useful!

What’s a Hard Link?

A hard link is essentially a name that links to data in the filesystem. Think about it this way, you have a file called crumbs.html, “crumbs.html” is essentially a name/hard link to the raw data that is stored within the file system. Within Linux it’s possible to create multiple links/names to the same raw data, resulting in the appearance of multiple files that take up no additional space. Each file the file-system contains a counter for how many hard-links point to it’s data, if this count reaches zero than the raw data can be written over (it’s deleted essentially).

How it’s going to work / The Code

In my machine I have two 2TB drives, the first one stores all of my data in the format and structure that I wish. The second drive, contains all of my backup data, sorted into folders (month/day/).

The concept is to sync all of the first drive’s data over to a directory on the second drive. Once this has completed, we created a hard-link copy of this folder, which acts as our snapshot.

#!/bin/bash

rsync -avh --delete /source/ /backup-location/latest/

cd /backup-location/
mkdir -p `date +%Y`/`date +%B`/`date +%d`/

cp -al /media/backup-2/latest/ /media/backup-2/`date +%Y`/`date +%B`/`date +%d`/

Encountered Questions

Why not use Symlinks moto?
Symlinks are useful for creating links to directories, however they create links based on the filename/hard link rather than the raw data itself. Hopefully the diagrams below help you spot the difference:

This is a Hard Link example
Hard Link
Symbolic Link
Symbolic Link