Showing posts with label backup. Show all posts
Showing posts with label backup. Show all posts

Wednesday, 23 June 2010

Script to do directory backups

It is usual to carry an external hard disk drive. As a portable device, it is prone to damage, can be stolen or corrupted by a virus. It is a good idea to have a backup of the contents of the portable HD in a laptop. I created a script written in BASH that helps me with this task.
The script does the following:
  • identifies the source directory (the original content)
  • identifies the destination directory (the place where you want to store the backup file)
  • the script stores the last 3 backup files. This means that, if a forth backup file is created, the script will erase the oldest backup file.
  • The script is executed manually. This is because the external hard drive is not always connected. Automatic execution may lead to errors because origin directory in not mounted on the filesystem.
The script goes as follows:

#!/bin/bash -x
#date: jun 21 2010
#backup of a directory in an external hard disk into laptop hard drive

BACKUPDIR=/home/EvilCat/WDBackup       

#this is the location where I want to store the backup 

SOURCE2=/media/WD\ Passport/My\ Documents/   
#this is the directory i want to do the backup

BACKUPFILE=backup.`date +%F_%R`.tgz           
#this is going to be the name of the backup file. 
#appends to the name the date and time the file was created

COUNT=`ls $BACKUPDIR/backup.* | wc -l`       
#counts the number of backup files that have been created. 
 
THRESHOLD=3 #the number of backup files to be stored.


if [ $COUNT -le $THRESHOLD ]
then
    tar -czf $BACKUPDIR/$BACKUPFILE "$SOURCE2"
    if [ $? != 0 ]

       then 
           echo problems creating backup file
    fi
else
    OLDFILE=`ls -ltr $BACKUPDIR/back* | cut -f 8 -d " " | head -n 1`
    rm -rf "$OLDFILE"
    tar -czf $BACKUPDIR/$BACKUPFILE "$SOURCE2"

fi



The script's name is backup.sh. In order to become executable, it must have the proper permissions. Your can set the permissions by issuing chmod u+x backup.sh. The script becomes executable.

At the moment, this utility syncs only one directory. Further work will involve a GUI, a way to select several folders to be backed-up and a mechanism to detect when the hard drive is connected and initiate a backup wizard.