sh ./autobackup.sh a1.txt usb/ 3
autobackup.sh=script name
a1.txt=file to be monitored
3=interval of checking in seconds
autobackup.sh
#!/bin/sh
#
# automatically creating a backup of a file if the any changes to the file occurs
# the script that automatically backs up everytime with an incremented number is needed
# Checks that /back exists
# Copies to specific USB directory# Checks if filename.bak exists on startup, copy if it doesn't
# 22/05/2018
if [ $# -ne 3 ] ; then
echo "Usage: autobackup filename USB-backup-dir delay"
exit 255
fi
# Create back directory if it does not exist
if [ ! -d back ] ; then
mkdir back
fi
FN=$1 # filename to monitor
USBdir=$2 # USB directory to copy to
DELAY=$3 # how often to check
if [ ! -f $FN ] ; then # if no filename abort
echo "File: $FN does not exist."
exit 5
fi
if [ ! -f $FN.bak ] ; then
cp $FN $FN.bak
fi
filechanged=0
while [ 1 ]
do
cmp $FN $FN.bak
rc=$?
if [ $rc -ne 0 ] ; then
cp $FN back
cp $FN $USBdir
cd back
sh ./createnumberedbackup.sh $FN
cd ..
cp $FN $FN.bak
filechanged=1
fi
sleep $DELAY
done
****************************************************
createnumberedbackup.sh
#!/bin/sh
#let me show you this script which is able to back up of files in the same directory and number
#the backup,in devops it is very common the save the project with revision number,this
#script is not that complex though
echo "Create Numbered Backup from files of the current directory given as argument"
if [ $# -eq 0 ] ; then
echo "Usage: sh ./createnumberedbackup.sh filename(s) "
echo " Will make a numbered backup of the files(s) given."
echo " Files must be in the current directory."
exit 255
fi
rc=0 # return code, default is no error
for fn in $* # for each filename given as arguments
do
if [ ! -f $fn ] ; then # if not found
echo "File $fn not found."
rc=1 # one or more files were not found
else
cnt=1 # file counter
loop1=0 # loop flag
while [ $loop1 -eq 0 ]
do
tmp=bak-$cnt.$fn
if [ ! -f $tmp ] ; then
cp $fn $tmp
echo "File "$tmp" created."
loop1=1
# end the inner loop
else
let cnt++ # try the next one
fi
done
fi
done
exit $rc # exit with return code
#every time you run this script with arguments if it finds backup file created by itself
#it will create the next backup with incrementing numbers so the backup can
#more organized
No comments:
Post a Comment