logotype

Using CRON to backup files in Ubuntu

 

With all the the fun and games I have been having playing with Ubuntu servers recently to host and manage websites and mail, it's probably time that I organized some proper form of backup. For the different servers I did things a little differently, one uses rsync to send the backups to a different machine, one has a USB drive mounted to store the backups. However for this guide I am simply going to explain how to write a shell script and get it running once a week with cron.

 

Step 1: Write the script to backup

First we need to create the .sh script, in general it can be stored in /usr/local/bin/ and I have called this one backup.sh. So open your favorite text editor and get to it!

sudo pico /usr/local/bin/backup.sh

The following script backups up the home directiory, mail, etc, root, boot, opt and www - so reasonably complete. Feel free to paste and change the code from my file:

#!/bin/sh
####################################
#
# Backup to NFS mount script.
#
####################################

# What to backup.
backup_files="/home /var/spool/mail /etc /root /boot /opt /var/www"

# Where to backup to.
dest="/bkup"

# Create archive filename.
thedate=$(date +%Y-%M-%d)
hostname=$(hostname -s)
archive_file="$hostname-$thedate.tgz"

# Print start status message.
echo "Backing up $backup_files to $dest/$archive_file"
date
echo

# Backup the files using tar.
tar czf $dest/$archive_file $backup_files

# Print end status message.
echo
echo "Backup finished"
date

# Long listing of files in $dest to check file sizes.
ls -lh $dest


We have placed in a few feedback calls so we can see it operate when we call it manually. To do so type the following:

 bash backup.sh

As you can see we have one file in there that was run by the current script (and four that were run by earlier scripts)

 

Step2: Run the script manually from CRON

So that is all well and good but we don't want to have to remember to run the script ourselves every week/day/hour etc. For that we will use CRON

To get it running its as simple as opening up the cron tab

sudo crontab -e

and adding the following line:

0 0 * * 1 bash /usr/local/bin/backup.sh

Explanation:

m          h      dom               mon    dow             command
Minute, Hour, Day of Month, Month, Day of week, the command to be run

So for ours we are running the command on minute 0, hour 0  for any day of the month, for any month on the first day of each week :-)

We now have a automatically running weekly backup of our site!

Copyright 2018 OReillyIT. All rights reserved.