penguin/utils

my env utils

bash/cronbackup/backup.sh

raw ยท 1687 bytes

#!/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]}"

			if [ -f $EXCLUDE ]; then
				tar zcf "$BAKDIR/$BACKUPFILE" -C "$FILE/../" $FILENAME -X $EXCLUDE
			else
				tar zcf "$BAKDIR/$BACKUPFILE" -C "$FILE/../" $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 7 backup
			if [ $fCount -ne 7 ]; then

				# delete count
				dCount=`expr $fCount - 7`
				
				# 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