Friday, September 18, 2009

Quick Backup Script

I often create scripts and programs (Perl mostly) to help me do things. When I'm developing these scripts, I will typically write a chunk of code, test it, add more functionality, test it, rinse, repeat.

However, there are times where I'll delete a chunk of code to try something different and end up breaking my entire script. Of course, when this happens I don't have a backup of the old code available to go back to.

To help me, I made this small script which will backup a file given to it to a directory. All it does is copy the file to a backup directory and tack on a date string to the end of it so every backup copy is unique. Yes, this is a simple copy, but it makes it nice to have to do things quickly.

#!/bin/bash

# quick script to backup files

DEFAULTDIR=${HOME}/backup
DATE=`date +%s`
if [ $# -lt 1 ] ; then
echo $0 file-to-backup [path to backup dir]
exit
fi

# set the backup dir location
BACKUPDIR=${2:-$DEFAULTDIR}

if [ ! -d ${BACKUPDIR} ] ; then
echo ${BACKUPDIR} did not exist. Creating.
mkdir -p ${BACKUPDIR}
fi

# make sure the file exists
if [ ! -f $1 ] ; then
echo $1 does not exist.
exit
fi

cp $1 $BACKUPDIR/${1}-${DATE}
if [ $? -eq 0 ] ; then
echo Successfully copied $1 to $BACKUPDIR/${1}-${DATE}
else
echo Error copying $1 to $BACKUPDIR/${1}-${DATE}
fi

I just copied it to /usr/local/bin, called it myback, and chmod +x'd it. Now, whenever I want to backup a script quickly I just run "myback script".

1 comment:

Shane said...

Here's what I do when I am about to modify a file and I want to save it in a versioned form.

#!/bin/ksh

if [ $# -eq 0 ]
then
echo "Usage: agefile filename"
exit 1
fi

while [ $# -ne 0 ]
do
base=$1

if [ -f $base ]
then
mv $base.11 $base.12 2> /dev/null
mv $base.10 $base.11 2> /dev/null
mv $base.9 $base.10 2> /dev/null
mv $base.7 $base.8 2> /dev/null
mv $base.6 $base.7 2> /dev/null
mv $base.5 $base.6 2> /dev/null
mv $base.4 $base.5 2> /dev/null
mv $base.3 $base.4 2> /dev/null
mv $base.2 $base.3 2> /dev/null
mv $base.1 $base.2 2> /dev/null
mv $base.0 $base.1 2> /dev/null
cp -p $base $base.0 2> /dev/null
fi

shift
done

exit 0