Scripting & Programming

Full Website Backup script including the MySQL database

This is a full website backup script including MySQL. It’s a bash script and it’s tested only on FreeBSD 6.3 but it should be working on any *BSD/Linux operation system. In order to make it work for linux you will need to change the paths for some commands.
For example:

have to be changed to:

Here is the code of the script:


#!/usr/local/bin/bash
#
#
# Full backup of website files and database content.
#
# Parameters:
# tar_file_name (optional)
#
# Configuration
#
# Database connection information
dbname=Database # (e.g.: dbname=database)
dbhost=localhost
dbuser=database-user # (e.g.: dbuser=MySQL_username)
dbpass=Password # (e.g.: dbpass=Mysql_user_password)
# Website Files
webrootdir=/path/to/web # (e.g.: webrootdir=/path/to/the/web/content)
#
# Variables
#
# Default TAR Output File Base Name
tarnamebase=website-backup-
datestamp=`/bin/date +’%d-%m-%Y’`
datestampinfo=`/bin/date`
# Execution directory (script start point)
startdir=/path/to/the/backup/folder
# Temporary Directory
tempdir=tmpbckdir$datestamp
#
# Input Parameter Check
#
if test “$1” = “”
then
tarname=$tarnamebase$datestamp.tar.gz
else
tarname=$1
fi
#
# Banner
#
/bin/echo “”
/bin/echo “BackUP started”
#
# Create temporary working directory
#
/bin/echo ” .. Setup”
/bin/mkdir $startdir/$tempdir
/bin/echo ” done”
#
# TAR website files
#
/bin/echo ” .. TARing website files in $webrootdir”
/usr/bin/cd $webrootdir
/usr/bin/tar -P -cf $startdir/$tempdir/filecontent.tar $webrootdir/
/bin/echo ” done”
#
# sqldump database information
#
/bin/echo ” .. sqldump’ing database:”
/bin/echo ” user: $dbuser; database: $dbname; host: $dbhost”
/usr/bin/cd $startdir/$tempdir
/usr/local/bin/mysqldump –pass=$dbpass –user=$dbuser –host=$dbhost –add-drop-table $dbname > $startdir/$tempdir/dbackup.sql
/bin/echo ” done”
#
# Create final backup file
#
/bin/echo ” .. Creating final compressed (tar.gz) TAR file: $tarname”
/usr/bin/tar -P -czf $startdir/$tarname $startdir/$tempdir/filecontent.tar $startdir/$tempdir/dbackup.sql
/bin/echo ” done”
#
# Cleanup
#
/bin/echo ” .. Clean-up”
/usr/bin/cd $startdir
/bin/rm -r $startdir/$tempdir
/bin/echo ” done”
#
# Exit banner
#
/bin/echo ” .. Website backup successfully completed on $datestampinfo”
/bin/echo “”


In addition you can create a cronjob on your system so the website backup can be scheduled. I hope I was helpful.

Leave a Reply