Simple WordPress backup script

For the purpose of backing up my wordpress installation, I have created a simple shell script to backup my mysql DB and content. I run it through cron for daily DB backups and weekly backups of everything, DB and files.

Script:
The script is expecting a parameter, daily or weekly, and based on the parameter it does only a daily SQL backup or a weekly backup of the DB and files.

#!/bin/bash
#
# WordPress backup script
#
#

# Backup variables from parameters
case $1 in
        daily)
          BACKUPDIR=/path/to/backup/wordpress/daily
          FILENAME=wordpress-`date +%Y%m%d`.sql.gz
          ;;
        weekly)
          BACKUPDIR=/backup/servers/heracles/sites/wordpress/weekly/$(date +%Y%m%d)
          FILENAME=wordpress.sql.gz
          WWWDIR=/var/www/
          WPDIR=wordpress
          ;;
        *)
          echo $"Usage: $0 [daily|weekly]"
          exit 1
esac

# Other Variables
DBNAME=dbname
USER=username
PASS=password

# Check if backup folder exists, if not, create it
if [ ! -d "$BACKUPDIR" ]; then
        mkdir -p $BACKUPDIR
fi

# Backup the DB
/usr/bin/mysqldump --add-drop-table -h localhost -u $USER -p$PASS $DBNAME | gzip > $BACKUPDIR/$FILENAME

if [ $1 = "weekly" ]; then
        tar czf $BACKUPDIR/wordpress.tar.gz --directory=$WWWDIR $WPDIR
fi

exit 0

I’ve then created simple scripts in /etc/cron.daily and /etc/cron.weekly that differ only in the parameter. They are being run once per day or week, depends on where you put them.

#!/bin/sh

SCRIPTDIR=/path/to/scripts
SCRIPT=wpbackup.sh
PAR=daily

$SCRIPTDIR/$SCRIPT $PAR

You may also like...

Leave a Reply

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