Backup Wordpress HTML and MySQL

by Vince
in Blog
Hits: 1317

This is something I should have done a long time ago.  I'm frequently hopping on a server and creating a manual backup prior to doing [something].  It's not like this task is complicated but as I was about to manually go through the steps this morning, I thought -- let's finally automate this process.

There's actually a one-liner for mysqldump but for some reason, it didn't work so I went a different route with the variables at the top which makes it a little easier when recycling this script on another server.


Spelling it out --

We're creating variables for MySQL username, password, and database.
We're creating a date variable.
We perform a sanity check to see if the backup folder already exists.
If the folder does not exist, we create the backup folder using our date variable and we create the subfolders.
We dump the MySQL database into the MySQL folder and we're suppressing the password warning message.
We copy the html directory into the html folder and we use diff to check for differences.
Finally, we wrap it up in a tar.gz file.

If the folder exists, you will see a message stating exactly that.  If the script runs and you don't see any messages, we're golden.  

# create USER variable
USER=root

# create PASSWORD variable
PASS="mys3cretp4ss"

# create DB variable
DB=wordpress

# create DATE variable
DATE=backup-"$(date +"%m-%d-%Y")"

# check if the backup folder already exists, if so, exit
if [ -d $DATE ]; then
    echo "Folder exists!!"
    exit 1
else

# create backup folders and subfolders
    mkdir -p $DATE/{html,mysql}
fi

# dump the database
mysqldump --opt --user=${USER} --password=${PASS} $DB > ./$DATE/mysql/$DB.sql /dev/null 2>&1

# copy the html directory, change to match your directory 
cp -r /var/www/html ./$DATE/

# check to see if there are differences between source and destination
diff --brief -Nr ./$DATE/html /var/www/html

# create an archive containing the db and files
tar -czf $DB.tar.gz $DATE