Regular backup with rsync and cron

This is nothing new, just for me to remember. We use rsync and cron to make a backup of all home directories regularly. There will be a weekly backup that is readily accessible and a zipped monthly backup.

First, we need to install rsync (this is for Ubuntu, replace with the package manager of your choice):

apt-get install rsync

Then we need to create the directories where we want to save the backups. Here I am putting it into /media/backup for no particular reason, use any directory you like.

mkdir /media/backup/weekly
mkdir /media/backup/monthly

Next the command that actually copies the files:

rsync -a --exclude=".*/" --delete /home/ /media/backup/weekly

The command uses rsync, which is the tool for the job. We want to backup the complete folder home with all the directories contained in there. We exclude hidden files (starting with .) to avoid copying .cache and other temporary files. You may want to refine this setting for your case. The option --delete overwrites the files in the target directory /media/backup/weekly. So last week’s data will be overwritten with this week’s data when the backup runs. I’d suggest running this command directly to see what happens before proceeding with the automation.

Now that we know how to copy the data, we just need to execute this command regularly. This is done with cron via this command:

crontab -e

This opens an editor with all cron jobs that are currently set up. Add two lines for the backup:

00 18 * * 5 rsync -a --exclude=".*/" --delete /home/ /media/backup/weekly
00 6 1 * * tar -cjf /media/backup/monthly/monthly_$(date +%Y%m%d).tar.bz2 /media/backup/weekly/

The numbers in the beginning of each line give the minutes, hours, day, month and day of the week. The rest of each line is the command. The first line copies the data to /media/backup/weekly on every Friday afternoon (at 18:00). So we will always have a backup that is at most a week old. The second line is executed on every first day of the month at 6:00 and copies the data to /media/backup/monthly in a zipped form.

This entry was posted in Linux and tagged , , , by swk. Bookmark the permalink.

About swk

I am a software developr, data scientist, computational linguist, teacher of computer science and above all a huge fan of LaTeX. I use LaTeX for everything, including things you never wanted to do with LaTeX. My latest love is lilypond, aka LaTeX for music. I'll post at irregular intervals about cool stuff, stupid hacks and annoying settings I want to remember for the future.