Taking backup of your files

Here is a small script that will automatically create a backup directory and take a backup of your files.

The script needs many improvements but, in its simplest form, I found it useful. I’ll improve it as and when I get some time.

#! /usr/bin/ksh
echo “Backing up $1”;
file=$1;
vDate=`date +%Y%m%d_%H%M%S%p`;
# User can mention relative or full path of the filename.
# in this case, extract the basename.
#fileName=split(‘/’,$1)
newFile=${file%\.*}_$vDate.${file##*.};
if [[ $1 = “” ]]
then
echo “Usage: backup <filename>”
exit;
fi
if ! [ -d ‘bkp’ ]
then
echo “bkp directory is not present. Creating the same.”
mkdir bkp;
fi
echo “copying $1 to bkp/${newFile}”;
cp $1 ./bkp/${newFile};
chmod -wx ./bkp/${newFile};

How to use this?

I have saved this script as “backup” and given it execute permission.

To take a backup of a file, run the following command at command prompt:

$ backup <filename>

This will first check if a directory “bkp” is present in the current directory. If not, it will create it and copy the file to it with name changed to reflect the date and time of copying.

Currently, it handles only one file at a time, I need to modify this to handle multiple files. But I guess I will do that in Perl instead of shell as it looks simpler.

Leave a comment