Snapshot backup using cp -al and rsync

This script requires genuine cp -al capable gnu and rsync commands together with a hardlink capable FS + OS.

 

 

#!/bin/bash

[ $# -ne 2 ] && echo "Incorrect usage : $0 <source path> <target path>" && exit 128 ;

SOURCEFOLDER=$1
TARGETFOLDER=$2

SF_LEN=${#SOURCEFOLDER}-1
TF_LEN=${#TARGETFOLDER}-1

#echo "Last character in source folder is ${SOURCEFOLDER:SF_LEN}"
if [ "${SOURCEFOLDER:SF_LEN}" != "/" ] ; then
   echo "Adding trailing slash"
  SOURCEFOLDER=$SOURCEFOLDER"/"
fi



#echo "Last character in target folder is ${TARGETFOLDER:TF_LEN}"
if [ "${TARGETFOLDER:TF_LEN}" != "/" ] ; then
   echo "Adding trailing slash"
  TARGETFOLDER=$TARGETFOLDER"/"
fi



echo $SOURCEFOLDER
echo $TARGETFOLDER

LOCKFILE=/tmp/`echo $0 $SOURCEFOLDER $TARGETFOLDER | sed "s/[^[:alnum:]]/_/g"`.lck
echo "Lockfile : $LOCKFILE"



[ ! -d $SOURCEFOLDER ] && echo "Source does not exist !! $SOURCEFOLDER exitting with error" && exit 1;

TIMESTAMP=$(date --utc +%Y%m%d%H%M )
#echo $TIMESTAMP



if [ ! -d $TARGETFOLDER ]; then 

mkdir $TARGETFOLDER

rsync -av --delete  $SOURCEFOLDER $TARGETFOLDER/$TIMESTAMP/

else 

[ -d $TARGETFOLDER/$TIMESTAMP/ ] && echo "Folder already there !! Leaving.. " && exit 0;  

 LASTBACKUP=$(ls $TARGETFOLDER | sort -rn | head -1)
 echo "Link copying $TARGETFOLDER/$LASTBACKUP to $TARGETFOLDER/$TIMESTAMP/"
 cp -al $TARGETFOLDER/$LASTBACKUP $TARGETFOLDER/$TIMESTAMP/
 rsync -av $SOURCEFOLDER $TARGETFOLDER/$TIMESTAMP/

fi

echo " OK !! Done"

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *