web dev & more!

WordPress Backup Bash Script

Published: January 5, 2018

I threw together a simple bash script to be run via cron jobs that will backup an entire WordPress site. Technically, it will work for a lot more than that assuming the site you’re backing up has a single directory to be backed up and a MySQL/MariaDB database. It’s a fairly simple script and it is easy to expand to work with multiple directories. Just take a look at the source for yourself!

To use, fill in the information at the top of the script (site name, database name, database user + password, path to site, and backup path), upload the script to `/etc/cron.daily/` on your server and you’ll be good to go!

Take note of the `SITE_PATH` variable at the top of the script. For whatever reason, there needs to be a space between the first ”/” and the rest of the path.

This script can also be found at https://gist.github.com/Dilden/70645ecd7feffdf914dbd0b92c3d6778

#!/bin/sh

THESITENAME=""
THEDB=""
THEDBUSER=""
THEDBPW=""
THEDATE=`date +%d%m%y%H%M`
# There is a space between the first `/` and the rest of the path in this variable
# It needs to be there for the TAR command to work for some reason
SITE_PATH="/ var/www/" 
LOCAL_BACKUP_PATH=""

# Backup MySQL DB
if mysqldump -u $THEDBUSER -p${THEDBPW} $THEDB | gzip > ${LOCAL_BACKUP_PATH}/db_${THESITENAME}_${THEDATE}.bak.gz
then
        echo "db backup successful \n";
else
        echo "db backup failed \n";
fi

# Backup $SITE_PATH directory
if tar czf ${LOCAL_BACKUP_PATH}/wp_${THESITENAME}_${THEDATE}.tar.gz -C ${SITE_PATH}
then
        echo "WP site backup successful \n";
else
        echo "WP site backup failed \n";
fi

# Remove files older than 2 days
find ${LOCAL_BACKUP_PATH}/wp_* -mtime +2 -exec rm {} ;
find ${LOCAL_BACKUP_PATH}/db_* -mtime +2 -exec rm {} ;


echo "backup complete $THEDATE \n"