Playing with Debian

Saturday, 15th March 2008 at 06:14pm

Use cron to automatically run scripts for you

After we talked about backing up your MySQL databases last time, I realised it would be much easier if I could just make my server back it up its self, every day. That way I don't have to think about it, and if I lose anything I can just revert to the last day's archive!

To do that, we use a thing call cron. This might have been called "cronjob" or something similar on your shared host, if you ever used it. If you did, then most of this should be obvious for you, since it's exactly the same (at least when I was using Plesk), just in a different way.

If you've ever looked around your /etc/ directory, you'd have noticed the /etc/cron.whatever directories. The files in there are run according to their directory, so the scripts in cron.daily are run once a day.

Each user has their own crontab file, which is where you put all the stuff you want to run. You can see your file with the command crontab -l (that's a lower case L). Chances are you won't have one just yet.

When you do though, it'll be laid out in six, space seperated fields, like this:

*     *     *     *     *  Command to be executed
-     -     -     -     -
|     |     |     |     |
|     |     |     |     +----- Day of week (0-7)
|     |     |     +------- Month (1 - 12)
|     |     +--------- Day of month (1 - 31)
|     +----------- Hour (0 - 23)
+------------- Min (0 - 59)

(Stolen from Debian Admin site, you should check out that article too.)

For day of the week, both 0 and 7 are Sunday, however some versions of Unix don't support 7.

To edit your crontab file, use crontab -e, which will open your crontab file in nano.

The "command to be executed" is the path to the command's binary (sorry if that makes little sense...), which you can find out by using the which command. For instance, if you want to run ls, you'd have to do which ls to find where it's kept. If you wanted to run ls, for some strang reason, you could do:

0   *   *   *   *  /bin/ls

Then, you'd get the output emailed to you, at your local user.

But, that's not what we want to do. We want to do a backup, each night. So, we'd add this:

10   23   *   *   *  "mysqldump -A -u root -p password > /home/shamess/backedup-files/$(date +%s).mysql"

That'll back all the databases up at 10 past 11 each night. The $(date +%s) part will output a Unix timestamp.

You'll probably want to delete really old back ups, and archive the new ones. You can do that by running a bash script, instead of a command, but we'll get to that later.

Comments

Your name: Your URL:

Body:

User comments

Marc says:

A most useful article, I've bookmarked this as i can never remember the exact syntax order of the values. Thanks!

shamess says:

I was planning on doing a cheat sheet post soon :)

Read some previous entries