Monday, December 5, 2016

How to take weekly backups using crontab on Linux

If you want to take automatic backup and save the backup files according to today's date(year,month,day), the command to use is,

tar cvzf `date +"%Y%m%d.tar.gz"` directory_that_you_want_to_backup

Here the file will be saved as YYYYMMDD.tar.gz in the current directory.

Now if you want to automate this command on a regular basis, you need to add it as a cron job on Linux.



Objectives:

The objectives of the example I'm writing on this post is simple. I want to make backups of the webroot of Apache HTTP server every week. I want to put the backup files under /backups/web directory. Let's see how it's done.

Note: Run all the commands as root.


Adding the command to cronjob:

To add the command to the cron job, run the following command as root.

crontab -e

A text editor should show up. Now add the following line to the end of the file.

@weekly /etc/cronscripts/weekly_web_backup.sh

Save the file and quit the editor.


Creating the script file:

There's a reason you should create script of everything you add on crontab file. Crontab file might throw some errors even when the command is correct. It happened to me once. So I always add a script file on crontab ever since. There's another advantage. You can put multi-line commands on a script file.

To create the script file, run the following commands.

mkdir -p /etc/cronscripts

It should create a new directory /etc/cronscripts. This is where I will put all my crontab scripts.

Now we should put the commands on the weekly_web_backup.sh file. To do that, open it as root with your favorite text editor and add the following lines.

#!/bin/bash

tar cvzf `date +"/backups/web/%Y%m%d.tar.gz"` /var/www &> /dev/null && echo "Backup taken"

What I am doing here is, I am taking backups of /var/www folder, archiving the folder with tar and putting it under /backups/web directory. The name of the file should be YYYYMMDD.tar.gz

Once you're done, save it.


Making the script executable:

Now we have to make it executable. So the crontab daemon can run it. To do that, run the following command.

chmod +x /etc/cronscripts/weekly_web_backup.sh

Making the directory where backups will be kept:

We also need the directory where backups will be kept. Without the directory, we won't be seeing any backups. But we should see lots of errors.

To create the directory, run the following commands.

mkdir -p /backups/web

Result:

Backup of /var/www directory should be taken every week and saved on a file YYYYMMDD.tar.gz in /backups/web directory.


References:

help.ubuntu.com



Tested on: Ubuntu 16.04 LTS

No comments:

Post a Comment