Friday, March 13, 2009

Backup utility in Bash Shell Script

save following bash shell script as mybackup.sh
#!/bin/bash

#

# Filename: mybackup.sh

# Author : Simrat Pal Singh

# Email : simrat.khokhar@gmail.com

#

# Modified: 02-03-2011

# to even work with paths having space

#


if [ $# -ne 2 ];then

echo "Wrong number of arguments"

echo "Usage: $0 /path/to/source /path/destination/"

exit 1

fi


input=$1

backupdate=$(date +%d%m%Y)

foldername=$(basename "$1")

inputpath=$(dirname "$1")

outpath="${2}"

output="${2}${foldername}_${backupdate}"


case ${foldername} in

*.tar.bz2)

[ "${inputpath}" = "" ] && inputpath="."i

bzip2 -dck "${inputpath}"/"${foldername}" | tar -C "${outpath}" -x

;;


*)

counter=0

while [ -f "${output}.${counter}.tar.bz2" ]

do

counter=$(expr $counter + 1)

done


output="${output}.${counter}"


# run tar and bzip2 command to make backup

tar -C "${inputpath}" -c "$foldername"|bzip2 -cz >"${output}.tar.bz2"

chmod -x "${output}.tar.bz2"

;;

esac


#--------------------- END ------------------------



execute with two arguments as:
sh mybackup.sh /path/source /path/destination/

it will create 'source_ddmmyyyy.x.tar.bz2' at /path/destination/
where 'x' is integer value, ie if you run it twice on same day for same source folder, it will automatically incremented.

if source folder is .tar.bz2, then it will unzip the contents at the destination path

1 comment: