Skip to content

How to automate your WordPress backups with a simple shell script

You have an established site, and after a lot of time well spent you’ve began to perfect the key of the e-lifestyle. But one day you go to login to your site and there is a problem. Your database is corrupt.

This is an all too common scenario in the web community nowadays but it can easily be averted. Following a few quick steps, or getting your site administrator to, can make backup an automated, set-and-forget issue. Even better, this is so simple even a novice can do it, and you have full control and understanding of what is happening with you data.

You may ask, why bother writing a “shell script” (whatever that is) when you can just install a backup plugin into WordPress and forget about it?

The answer is security. With a few simple commands, I will have a script that does its job, does it well, does it quickly, and updates me if anything goes wrong. Plus, you know exactly what the script is doing. Not to freak anyone out, but if you are putting your private server password into a plugin, guess what, the plugin author could easily get access to your machine. In my experience, most developers are honest and would never do such a thing, but there still remains a possibility.

By the way, I’m using this for WordPress, but it could work for any website, based on any CMS, or none at all, with DB or without.

If you haven’t already, please read my tutorial on How to mirror a WordPress site between a web server and a desktop testbed server. That will explain the conceptual process and explain in more detail where the some of the commands in this tutorial is coming from.

First things first; here’ s the script:

backup.sh

tar -czf /home/yoursite_files.tar.gz yoursite

mysqldump --add-drop-table -h localhost -u dbuser -pPassword wordpressdb | gzip > wordpressdb.gz

Now that we have the script, let’s dissect it a little:

By running /home/myuser/scripts/backup.sh, the functionality of the script can be confirmed. Still, it’s not too automated. The script can be called automatically from a cron job. To setup a cron job, edit your user’s crontab  file by executing the command crontab -e, and drop this lines in it:

/home/user/backup.sh

With that, you now have an automated backup. If anything goes wrong, it will email your root account.

Published inDevelopment