WordPress Backup Script

This is a small script I’ve written to automate my server-side backups of my blogs. It creates a backup of both the database and the actual WordPress files.

#!/bin/bash

# (C) 2008 Guy Rutenberg - http://www.guyrutenberg.com
# This is a script that creates backups of blogs.

DB_NAME=
DB_USER=
DB_PASS=
DB_HOST=

#no trailing slash
BLOG_DIR=
BACKUP_DIR=


echo -n "dumping database... "
mysqldump --user=${DB_USER} --password=${DB_PASS} --host=${DB_HOST} ${DB_NAME} 
 | bzip2 -c > ${BACKUP_DIR}/${DB_NAME}-$(date +%Y%m%d).sql.bz2
if [ "$?" -ne "0" ]; then
    echo -e "nmysqldump failed!"
    exit 1
fi
echo "done"


echo -n "Creating tarball... "
tar -cjf ${BACKUP_DIR}/${BLOG_DIR##*/}-$(date +%Y%m%d).tar.bz2 ${BLOG_DIR}
if [ "$?" -ne "0" ]; then
    echo -e "ntarball creation failed!"
    exit 1
fi
echo "done"


Copy the above code and save it to a file called backup-blog. Before you can use it, there are some configurations to be done. At the beginning of the script (right after the copyright notice), you will find some variables you need to set.

The first set of variables is the database configuration. Set DB_NAME to the name of your database, DB_USER to your database username, DB_PASS to the user’s password, and DB_HOST to the hostname of the database server. For most users, DB_HOST should be set to localhost (but some users need to specify a different value here).

The next variable is BLOG_DIR. Set it to the full path of the directory where you installed WordPress. BACKUP_DIR should be set to the full path of the directory you want to keep the backups in; make sure the user who will run the script has write access to it. Notice that both paths shouldn’t end with a trailing ‘/’ (slash).

Now that the configuration is over, make the script executable:
chmod +x backup-blog
Now you can test that everything works OK by running the script: ./backup-blog. If the script fails for some reason, make sure your configuration is correct.

The next step is to automate the backup process using cron. Run crontab -e to add an entry for the backup script. Append the following line to the crontab:
30 1 * * 4 /path/to/backup-blog
This will run the script automatically for you once a week, at 01:30 AM every Friday. Be sure to check the backup folder from time to time to make sure everything is running smoothly.

Note that while the script was originally intended to create backups of WordPress blogs, it can also be used to back up any kind of website that needs both file and database backups, like MediaWiki, Drupal, or almost any kind of CMS or blogging platform.

2 thoughts on “WordPress Backup Script”

Leave a Reply

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