(Automated) Manual Backup of a WordPress Blog (Including the Database)

I wrote my own shell script to create a backup of this WordPress blog as I was not happy with the ready to use backup plugins for WordPress such as wp Time Machine.

The script creates two files during the backup process. One that contains all the files in the installation directory of the WordPress installation (so the PHP files including the additional modules, the .htaccess file etc.). The other file contains the SQL dump of the MySQL database used by WordPress (all the tables! If you have tables of other web applications stored in that database, those will be included in the backup!).
So here it is, the script that I run on the server where I have the WordPress blog installed in /var/www/blog to back the installation up into the directory ~/blog-backup:

#!/bin/sh

####################################################################
#
# Wordpress Backup
#  inspired by <https://gist.github.com/737577>
#
####################################################################

#################
# RESTORE INFO: #
#################
# restore the WordPress installation folder: move the tar to blogdir and run tar -xf file.tar
# restore the database: gunzip -c blog-timestamp.sql.gz | mysql dbname>

###############################################
# CHANGE THESE OPTIONS TO MATCH YOUR SYSTEM ! #
###############################################

blogdir=/var/www/blog # the directory the wordpress blog is installed in
backupdir=~/blog-backup # the directory to write the backup to

## To debug this script, uncomment the following line to see the commands as they are being executed:
#set -x

##################
# END OF OPTIONS #
##################

test ! -d $backupdir && mkdir $backupdir
blogDBserver=`grep '^define' $blogdir/wp-config.php | grep 'DB_HOST' | cut --delimiter="," -f2 | cut --delimiter="'" -f2`
blogDBname=`grep '^define' $blogdir/wp-config.php | grep 'DB_NAME' | cut --delimiter="," -f2 | cut --delimiter="'" -f2`
blogDBuser=`grep '^define' $blogdir/wp-config.php | grep 'DB_USER' | cut --delimiter="," -f2 | cut --delimiter="'" -f2`
blogDBpassword=`grep '^define' $blogdir/wp-config.php | grep 'DB_PASSWORD' | cut --delimiter="," -f2 | cut --delimiter="'" -f2`
blogdb=$blogDBname
mysqlopt="--host=$blogDBserver --user=$blogDBuser --password=$blogDBpassword --skip-lock-tables"

timestamp=`date +%Y-%m-%d`

dbdump="$backupdir/blog-$timestamp.sql.gz"
filedump="$backupdir/blog-$timestamp.files.tgz"

echo "WordPress blog backup. Database: $blogdb; Directory: $blogdir; Backup to: $backupdir"
echo
echo "creating database dump $dbdump..."
mysqldump --default-character-set=utf8 $mysqlopt "$blogdb" | gzip > "$dbdump" || exit $?

echo
echo "creating file archive $filedump..."
cd "$blogdir"
tar -zcf "$filedump" . || exit $?

echo
echo "Done!"
echo "Files to copy to a safe place: $dbdump and $filedump"

#######
# END #
#######

Comments