Tutorial: Backup script

Terminal

The importance of running a thorough, regularly scheduled back up cannot be overstressed regardless of whether your site is just starting out or has hundreds of viewers per day. Backing up your important files goes a long way towards preventing or easily repairing many headaches that may come along with broken installations or updates, hacking attempts or if you simply want to move to another domain or hosting provider. After all, an ounce of prevention is worth a pound of cure. In this post, I will show you a basic script you can use as part of your scheduled back up. It will copy your website to a backup folder, zip the contents of the folder and optionally keep a working mirror of your website–automagically!

Why backup?

The problem with backing files up is that most people just don’t see the need to do so until something has happened. Unfortunately, by then it’s usually too late to fix the problem. In reality, if you do not have your website scheduled for a regular daily backup, you are playing a dangerous game Russian roulette with your information. Once a routine backup plan is put into effect, it will give you the peace of mind that comes along with knowing that if problems should occur, you will have… a back up!

Most hosting providers do back up everything on their servers, but that doesn’t necessarily mean they do it often. They may backup the operating system and important information to keep the server running on a daily basis, but most don’t run daily backups of the websites they are hosting. To be honest, it’s just not worth the disk space for them–there could literally be hundreds, even a thousand websites being hosting on a shared server. Of those that do run backups, many charge for restoring the back up they have on copy and it may be weeks or a month old at best. To be honest, they maintain back ups for themselves. It’s your responsibility to back up your own information.

Paid versus shell scripts

There are many back up solutions that rely on the software you have installed on your site. A quick search will bring up a plethora of paid and free plugins available for OsCommerce, Wordpress, CRE Loaded, Joomla, etc. There is a problem with these plugins, though: most rely on your installation to work or be somewhat functional and they run the risk of breaking if you update the plugin or the software. While they are generally much easier to use, they are not the most effective way to back up your site and some only back up the specific software installation, not any other files you may be hosting.

So, how do you get around this? The answer is very simple: good, old reliable shell scripts. Shell scripts have been around forever and they are without a doubt the most reliable way of backing up your information. They aren’t as user friendly as web site plugins, but they are free, fast, have a proven track record and there is a wealth of information available about how to use them. They do not rely on anything to be installed except, of course, the operating system your host is running, but that’s assumed. Since they run locally where your information is stored, they are faster than downloading and backing up your site via FTP. It is nice to have a copy of your site downloaded via FTP on hand in case of a major disaster and I do recommend this as well, but that’s for another topic.

Getting started

Before you do anything, though, you need to make sure you have: SSH (shell access) and the ability to run CRON jobs. Godaddy, for example, requires you to activate SSH by phone before you can run CRON jobs, and since you need both, you should go ahead and get it activated before continuing to read. The back up I will show you has been tested on Godaddy via SSH and their CRON job manager, but should work just as well on any other hosting provider that runs Linux with little or no modification necessary. The first script is designed for Wordpress and selectively backs up only Wordpress and any files in the immediate root directory. It assumes that you have installed Wordpress in the root directory. For example: http://www.yourblog.com NOT http://www.yourblog.com/wordpress. The second script can be used for backing up your entire web site–it merely backs up everything in the public html directory. Again, you can easily modify these scripts to suit your needs. You need only to change the directory or directories that you wish to back up in the scripts.

Plan of action

  1. Create a directory in your root called ‘backups’
  2. Create another directory inside backups called ‘dailyback.’
  3. Protect backups with a user name and password using .htaccess and .htpasswd.
  4. Create an empty file inside backups with a plain text editor (no Microsoft Word et al–Notepad or gedit are good enough!) call it backup.sh since this is a shell script we’re creating.
  5. Into the contents of this file, copy and paste the following script:

#!/bin/bash
#Compliments of www.fortasse.com
#Displays a greeting and backs up files
#Begin Script
TERM=linux
export TERM
NOWDATE=`date +%m%d%y` # Sets the date variable format for zipped file: MMddyy
clear # clears terminal window
echo
echo "Hi, $USER!"
echo
echo "Beginning backup of files @ `date`"
echo "Backing up wp-content..."
#Copy wp-content
cp -r $HOME/html/wp-content $HOME/html/backups/dailyback
echo "Done!"
echo
#Copy wp-admin
echo "Backing up wp-admin..."
cp -r $HOME/html/wp-admin $HOME/html/backups/dailyback
echo "Done!"
echo
echo "Backing up wp-includes..."
#Copy wp-includes
cp -r $HOME/html/wp-includes $HOME/html/backups/dailyback
echo "Done!"
echo
echo "Backing up files in Wordpress the root folder /html/ ..."
#Copy miscellaneous files in /html/ only
cp $HOME/html/*.* $HOME/html/backups/dailyback
echo "Done!"
echo
echo "Zipping directory structure..."
tar -cvzf $HOME/html/backups/$NOWDATE.tar.gz $HOME/html/backups/dailyback/*
echo "Backup complete!"
#Uncomment the following lines if you DO NOT want to keep a mirror of your site:
#echo "Cleansing backup folder..."
#rm -r $HOME/html/admin/dailyback/*

You will need to do a couple of things before you can run this. If you’re on Godaddy, you shouldn’t need to make any changes to the script. If you’re not on Godaddy, you might need to change the /html/ folder to /public_html/ or whatever it is that your host uses. Make any other changes you need to the directory structure and uncomment the last two lines if you don’t want to keep a working mirror of your Wordpress blog. Upload it to your web site and test it out by opening an SSH connection and going to the directory you uploaded it to and type:
cd ~/html/backups
sh backup.sh

Technically, you don’t need to do all of that copying. You could simply remove almost everything but the last line and tell the script what directory you want to backup. However, I prefer to keep both a working copy (aka mirror) and a zip at all times. It’s a lot faster to simply copy the mirror back over if something broke than to have to unzip and restore the archive. Let’s look at an example of a barebones script that simply zips everything in the public html folder:

#!/bin/bash
#Compliments of www.fortasse.com
#Displays a greeting and backs up files
#Begin Script
TERM=linux
export TERM
NOWDATE=`date +%m%d%y` # Sets the date variable format for zipped file: MMddyy
clear # clears terminal window
echo
echo "Hi, $USER!"
echo
echo "Beginning backup of files @ `date`"
echo
echo "Zipping directory structure..."
#Remove the v in -cvzf below if you don't want to see the output
tar -cvzf $HOME/html/backups/$NOWDATE.tar.gz $HOME/html/*
echo "Backup complete!"

In this case, everything in the public html folder was zipped and the corresponding zip file placed in the ~/html/backups/ directory. This is really effective if you don’t want to selectively back up certain files or directories. I run several backups on my server, at different rates and times and for specific files or directories. Not every web site hosted on my account will necessarily go down at the same time. Therefore, making individual back ups of different installations and/or web sites allows me to have a much finer degree of control over my backups. If I zipped the entire site in one file, I would have to worry about over-writing new content on other unaffected web sites contained in the same root when I expand the zip file. That would be another nightmare altogether!

Backing up your database with MySQLDump

Backing up your database is also very important. If your database goes, in most cases you’ll having nothing. Zilch. Zero. No posts, no users, no links, no tags. You get the point. Thankfully, this is fairly easy to do using a shell script.

Do it!

  1. Create a directory called ‘database’ inside the the /html/backups directory.
  2. Copy and paste the following code into the bottom of the backup.sh script.

echo "Backing up Wordpress database"
mysqldump -h YOUR.DBSERVER.COM -uUSERNAME -pPASSWORD DATABASENAME > $HOME/html/backups/database/$NOWDATE.sql
gzip -9 $HOME/html/backups/database/$NOWDATE.sql
echo
echo "Job finished!"

Replace YOUR.DBSERVER.COM with wherever your database is stored. It might be locally stored on the machine, or it could be located on a remote server in the case of Godaddy. Replace USERNAME with your username, PASSWORD with your actual password and DATABASENAME with the name of the database you want to backup. Keep the spaces, all dashes and everything else you see intact. -p and PASSWORD are supposed to be connected. Do not make a space between them, or it may not work. Like the file back up script, this will back up the database, zip it and put it in an archive with a time stamped file name.

Final steps

You will need to set this script to run through your hosts CRON Job manager. In Godaddy, this is a very simple task. You need to upload the file, open up your Hosting Control Center, go to Cron Jobs and select the file and time you wish to run the shell script. NOTE: You may get a ‘Permission Denied Error!’ In this case, try setting the permissions of the backup.sh file to 755. For other hosting companies, you may or may not have to use CRON Tab or some other CRON job manager. The commands are simple, but call your hosting company if you have any questions. In either case, you should set up the job to send you an e-mail upon completion. At least for the first few days, to make sure the script is working properly. Caveat: If you left to verbose (-v option) on for tar, you may get a very large e-mail.

Summary

So to briefly summarize everything, the first script copies specific directories, creates a mirror and zips the mirrored backup and places it in a backup directory. The file name is the time stamp of the backup date. The second script backs up everything in your public html file (all websites, subdomains, and anything else) and zips it up and does not create a mirror image of your site. The third will backup your SQL database and zip it in a nice little file using gzip. Simple enough, huh?

If all went as planned, you should have a working back up script for your website. I recommend using the script at least daily for the best protection. Enjoy!

4 Comments

  1. Not quite the topic, but your web site loads really slow. Something bad with your server ?

  2. There are some issues with the CSS styling and compression on the site. I am working on fixing these issues ASAP.

  3. Just want to say your article is striking. The clarity in your post is simply striking and i can take for granted you are an expert on this subject. Well with your permission allow me to grab your rss feed to keep up to date with forthcoming post. Thanks a million and please keep up the ac complished work. Excuse my poor English. English is not my mother tongue.

  4. Do have an email system where I can get your blog posts emailed to me?

Leave a Reply

Get Adobe Flash playerPlugin by wpburn.com wordpress themes