File backup script


Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /www/chergeek/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

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 the_script.sh sync
# Full backup
sh the_script.sh save

My crontab is:

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

The script is below:

#!/bin/bash
# Shell script to backup content
# Written by Titouan13
 
# Main directory where backup will be stored
MBD="/backup/content"
 
# Directory for incremental backups
INC="$MBD/incremental"
 
# Folder to backup 
SRC="/your/path/"
 
# Get data in dd-mm-yyyy format
NOW="$(date +"%d-%m-%Y")"
 
# File name
FILE="your_website"
 
# RSYNC on both folders to update the content
if [ "$1" == "sync" ] ; then
	echo "RSYNC backup"
	rsync -avh --delete $SRC $INC
fi
 
# 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/*
	else
		# Get the content and compress it every week
		tar -cpzPf $MBD/weekly/$FILE.$NOW.tar.gz $INC >> /tmp/mail_report.log
	fi
 
	end=`date +%s%3N`
	runtime=$((end-start))
	echo Runtime: $runtime"ms" >> /tmp/mail_report.log
 
	mail -s "Backup content "$NOW your_email_address@xxx.com < /tmp/mail_report.log
fi

Leave a Reply

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