utils/bash/cronbackup/backup.sh
2014-07-29 09:53:10 +08:00

97 lines
1.8 KiB
Bash

#!/bin/bash
source ./config.sh
# IO Redirection
exec > $LOGFILE
exec 2> $ERRLOG
if [[ -n $BMOUNT ]] && ! grep -qs $BMOUNT /proc/mounts; then
echo Mounting $BMOUNT ...
mount $BMOUNT
MOUNTED=$?
fi
if ! [ -d $BAKDIR ]; then
mkdir $BAKDIR
fi
echo Begin backup schedule:
echo Date: $(date)
while read line; do
# substring first char
firstChr=${line::1}
# if line is not empty and does not start with "#"
if [ $firstChr ] && [ $firstChr != "#" ]; then
# file and arguments are seperated by ":"
IFS=':' read -ra ARGS <<< "$line"
# Get file
FILE=${ARGS[0]}
# if file exists
if [ -a $FILE ]; then
# filename
FILENAME=$(basename $FILE)
# set the backup name YYYYMMDDhhmm
BACKUPFILE=$(date +$FILENAME.%Y%m%d%H%M.tar.gz)
# exclude file
EXCLUDE="exclude/${ARGS[1]}"
CHDIR=$(dirname $FILE)
if [ -d $FILE ]; then
CHDIR="$FILE/../"
fi
if [ -f $EXCLUDE ]; then
tar zcf "$BAKDIR/$BACKUPFILE" -C $CHDIR $FILENAME -X $EXCLUDE
else
tar zcf "$BAKDIR/$BACKUPFILE" -C $CHDIR $FILENAME
fi
# count backup file
fCount=$(ls $BAKDIR/$FILENAME.[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9].tar.gz|wc -l)
echo " Check for existing backups "$FILENAME \(Have: $fCount\)
# keep up to X backups
if [ $fCount -ne $KEEP ]; then
# delete count
dCount=`expr $fCount - $KEEP`
# loop over files
for files in $BAKDIR/*$FILENAME*.gz; do
if [ 0 -lt $dCount ]; then
# remove expired file
echo " Removing expired backup: "$files
rm "$files";
# dCount --
dCount=$((dCount-1));
fi
done
fi
fi
fi
# echo --\> $line
done < backup_list
if [[ "$MOUNTED" = 0 ]]; then
umount $BMOUNT
fi