File backup script

We all care of our stuff and need to back it up. I recently set up a system to automatically do it. I use crontab to perform backups as long as I want.

It is divided in two parts. The first one is with rsync to do an incremental update. The second one is a backup with gzip compression to save and eventually export to another server.

Only the second part send an email to recap because the rsync part can be performed many times a day if you’d like.

In the following case, make sure you create folders (incremental, weekly and monthly) and gave the appropriate rights to your backup folder (i.e. /backup/content) which are “chmod -Rf 0600 /backup/content”. You don’t want anyone to access it except root.

The use of this script is very simple:

# Rsync backup
sh sync
# Full backup
sh save

My crontab is:

# Once every week, on monday at 4:30, I save
30 4 * * mon sh save
# Three times a day, every 8h, I sync
0 */8 * * * sh sync

The script is below:

# Shell script to backup content
# Written by Titouan13
# Main directory where backup will be stored
# Directory for incremental backups
# Folder to backup 
# Get data in dd-mm-yyyy format
NOW="$(date +"%d-%m-%Y")"
# File name
# RSYNC on both folders to update the content
if [ "$1" == "sync" ] ; then
	echo "RSYNC backup"
	rsync -avh --delete $SRC $INC
# Full backup with gzip files and sending email report
if [ "$1" == "save" ] ; then
	start=`date +%s%3N`
	NB_FILES="$(ls -1 $MBD/weekly | wc -l)"
	# Perform one backup every four week and delete older weekly backups
	if [ "$NB_FILES" > "3" ] ; then
		echo "4 weeks backup" >> /tmp/mail_report.log
		tar -cpzPf $MBD/monthly/$FILE.$NOW.tar.gz $INC >> /tmp/mail_report.log
		rm $MBD/weekly/*
		# Get the content and compress it every week
		tar -cpzPf $MBD/weekly/$FILE.$NOW.tar.gz $INC >> /tmp/mail_report.log
	end=`date +%s%3N`
	echo Runtime: $runtime"ms" >> /tmp/mail_report.log
	mail -s "Backup content "$NOW < /tmp/mail_report.log

Leave a Reply

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