Automating Your Backup with Cron

This post is part of a series on automatically backing up your website:

What Is Cron?

alarm clock
cron is a daemon that will execute commands at a scheduled date and time. You use the crontab command (short for cron table) to set up cron to execute commands at regular intervals.

If you haven’t used cron before, I recommend reading this excellent introduction to cron and crontab and looking at this example crontab file. You should have at least a basic understanding of crontab before proceeding.

Configuring Crontab

Now that you know how to backup your web site, let’s schedule automatic backups using crontab. Open up your crontab file (note: don’t edit your crontab file directly):

sudo crontab -e

Add a line that will trigger astrails-safe to backup your files. Here’s how I have’s backup set up:

15 04 * * 1,4 /usr/local/bin/astrails-safe /etc/astrails-safe/techiferous.rb > /var/log/cron/techiferous-`date "+\%Y\%m\%d_\%H\%M"`.log 2>&1

Let me break that down for you:

15 04 * * 1,4 This tells cron to run the command every Monday and Thursday at 4:15am.
/usr/local/bin/astrails-safe /etc/astrails-safe/techiferous.rb This is the command that backs up your web site. Notice that I preceded astrails-safe with /usr/local/bin. This is because crontab sets up a bare environment, meaning astrails-safe is not in the default PATH. To get around this, I explicitly specified the full path.
> /var/log/cron/techiferous-`date "+\%Y\%m\%d_\%H\%M"`.log This instructs stdout to be saved to a log file. That helps us debug crontab when things go wrong. Note that I’m automatically generating a timestamped filename.
2>&1 This Unix idiom tells stderr to go to the same place as stdout. Otherwise, errors would not appear in the log file.

If you set up your crontab similarly, make sure the /var/log/cron directory exists or your backup will not run.

The End

That’s it! Now you can sit back and relax while your web server backs up your website for you automatically.

You can leave a response, or trackback from your own site.

One Response to “Automating Your Backup with Cron”

  1. Bharat says:

    This is awesome Wyatt. Very well written indeed.

Leave a Reply