Wednesday, 21 March 2007

Linux: A simple backup script

Here is the script I use for backing up my home directory onto the hard drive an other machine (mounted using samba). The script can be configured by changing the values of the top variables

#!/bin/bash
# Script to back up my home directory
# Created 21-03-2007
# Thanassis Bakalidis

BKP_FILE="/mnt/KomUsers/bakalidi/LinuxBackups/my_home.tar.bz2"
BKP_ROOT="/home/thanassis"
LOG_FILE="/home/thanassis/backup_output.txt"
EXCLUDE_FILES_FILE="/home/thanassis/.files_to_exclude"
ERROR_FILE="/home/thanassis/backup_errors.txt"

EXCLUDE_DIRS="/home/thanassis/mp3 /home/thanassis/java"

# remove file if existing
if [ -f $EXCLUDE_FILES_FILE ]; then
 rm $EXCLUDE_FILES_FILE
fi

# get a list of all file patterns that do not need be backed up
for path in $EXCLUDE_DIRS
do
 echo $path/\* >> $EXCLUDE_FILES_FILE
done

# finally append the log file in the list of excluded files
echo $LOG_FILE >> $EXCLUDE_FILES_FILE
echo $EXCLUDE_FILES_FILE >> $EXCLUDE_FILES_FILE

# start the log File
echo Backup of $BKP_ROOT Starting at `date` > $LOG_FILE

# after creating the list of files to be excluded perform the actual backup
/bin/tar -jcvf $BKP_FILE -X $EXCLUDE_FILES_FILE --exclude-caches  $BKP_ROOT  1>> $LOG_FILE 2>$ERROR_FILE

# mark the end time stamp on the log file and exit
echo Backup of $BKP_ROOT finished at  `date` >> $LOG_FILE
exit 0

It is true that one could directly edit the $EXCLUDE_FILES_FILE and add the patterns of the files that should not be backed up. Personally, I prefer the approach shown above, because that way I keep all my information regarding backups in one place and thus have less configuration files to worry about-- Of course there is always more than one way to do things right.

Finally I have added the following in my crontab config :

thanassis@lxbakalidis:~> crontab -l
# DO NOT EDIT THIS FILE - edit the master and reinstall.
# (/tmp/crontab.XXXXhnhNTc installed on Wed Mar 21 11:52:39 2007)
# (Cron version V5.0 -- $Id: crontab.c,v 1.12 2004/01/23 18:56:42 vixie Exp $)
30 18 * * * /home/thanassis/bin/tarbackup.sh

The /mnt/KomUsers speciffied as target in script file directory points to the users folder of a Windows 2003 server on my local area network. The company administrator runs tape backup jobs at exactly 19:00 everyday, so starting my backup at 18:30 allows me to keep a copy of my data every day in a separate tape following the day, week, month company schedule.

No comments :