Cron Task For Automated Backups

What we’re going to cover in this tutorial, is how to set up a cron job on a Centos 5 linux server. The basic problem I had, was that our server’s /backup/cpbackup/ folder was getting filled with (automated) backups very fast, taking up tonnes of disk space very quickly (only 7.5GB total available on this VPS! – perhaps time to look for a better one?). We’ll learn how to use cron jobs here to achieve the following:

  • Execute a script at a specified time once a week, which peforms the following:
  • Create a zipped-tar backup of the folder /backup/cpbackup/ at /backup/cpbackup_ddmmyy.tar.gz
  • Clear the entire /backup/cpbackup/ folder of all contents, freeing up this space
  • Email the administrator that the new backup_x.tar.gz file has been created
  • (Optionally): Automatically copy this file over to another (larger capacity) server

Step 1: Install A Cron Task

A great little tutorial showing exactly how easy it is to install a cron task on any linux system, can be found here.

Step 2: Create the Shell Script

The script which performs the magic, looks like this:

#!/bin/sh
# Create a zipped-tar backup of the folder /backup/cpbackup/ at /backup/cpbackup_ddmmyy.tar.gz
# Clear the entire /backup/cpbackup/ folder of all contents, freeing up this space
# Email the administrator that the new backup_x.tar.gz file has been created
# (Optionally): Automatically copy this file over to another (larger capacity) server
 
EMAIL="youremail@gmail.com"
NOW=$(date +"%d-%b-%y_%H%M")
BFILE="/backup/wz_cbackup_$NOW.tar.gz"
MSG=""
SUBJECT=""
 
#create tar zip file:
tar -czf $BFILE /backup/cpbackup/
 
if [ "$?" -ne "0" ]; then
	MSG="tar -czf $BFILE /backup/cpbackup/ failed."
	SUBJECT="weeklyZip: $BFILE creation failed!"
else
  	MSG="$BFILE successfully created. Please either download or copy to new server."
  	SUBJECT="weeklyZip: $BFILE  successfully created."
 
	#Success, so we clear out the /backup/cpbackup/ folder:
	rm -R /backup/cpbackup/* -f
fi
 
/bin/mail -s "$SUBJECT" "$EMAIL" <<< "$MSG"

Linux Shell Scripting: Check if Folder Exists

If we want to check if a folder exists we simply create the following .sh file:

#!/bin/bash
 
if [ ! -d "myFolder" ]; then
	echo "Creating myFolder"
	sudo mkdir myFolder
fi
 
if [ ! -d "myFolder/subFolder" ]; then
	echo "Creating myFolder/subFolder"
	sudo mkdir myFolder/subFolder
fi

Now you can run that using sudo and for example create a new folder where one didn’t exist before, if its required by some other script, for example one mounting a windows XP drive over a network to the current Linux filesystem using Samba. See the post covering that for more details.