Quantcast
Viewing all articles
Browse latest Browse all 20

Back up. Stress down.

Here’s a simple backup script to drop onto your Linux based server. It’ll back up and rotate file names, once a day.

I wanted something simple but powerful. It just requires the ubiquitous date command, present in most systems, but will keep enough backups to cover most situations. One per month over 12 month rotation, one per week over 5 week rotation, and one per day over seven day rotation.

The code simply uses the fact that the days and months change in a predictable way. For instance Monday comes around every seven days, so a file called Monday will be replaced every seven days if we try to save another file called Monday, as with all the days, simply replacing older files.

It’s on my BitBucket here:
https://bitbucket.org/akademy/backup-script/src/master/
which you can check out for more details. But also see the code below.

backup_rotate_store () {

	local usage
	usage="Usage: 'backup_rotate_store <directory> <original_filename>'.
The original file should be in <directory>. Pass in the current name of the file."

	# Check for parameter $1
	if [ -z "$1" ]
	then
		echo "First parameter not set to a directory"
		echo "${usage}"
		return 1
	fi

	# Check for parameter $2
	if [ -z "$2" ]
	then
		echo "Second parameter not set to original filename"
		echo "${usage}"
		return 1
	fi

	local directory
	directory=$1
	local original_filename
	original_filename=$2

	local DAY
	DAY=$(date +%A)

	# Day backupds (Sunday, Monday, etc.)
	mv "${directory}/${original_filename}" "${directory}/${DAY}.${original_filename}"

	local DATE=
	DATE=$(date +%d)
	if (( $DATE == 1 || $DATE == 8 || $DATE == 15 || $DATE == 22 || $DATE == 28 )); then

		local EXTENSION
		EXTENSION='th'
		if (( $DATE == 1 )); then
			EXTENSION='st'
		fi
		if (( $DATE ==22 )); then
			EXTENSION='nd'
		fi

		# Weeks backup (1st, 7th, etc.)
		cp --archive "${directory}/${DAY}.${original_filename}" "${directory}/${DATE}${EXTENSION}.${original_filename}"

		if (( $DATE == 28 )); then
			local MONTH
			MONTH=$(date +%B)

			# Months backup (January, February, etc.)
			cp --archive "${directory}/${DAY}.${original_filename}" "${directory}/${MONTH}.${original_filename}"
		fi

	fi
}

To use it, just move the file to backup to where it should be stored then call the function. e.g.:

echo "My backup testfile" > testfile

DEST=/data/backups
FILENAME=testfile.txt

mv testfile "${DEST}/${FILENAME}"

backup_rotate_store ${DEST} ${FILENAME}

Enjoy, and may it bring you luck.

Share This:


Viewing all articles
Browse latest Browse all 20

Trending Articles