Monday, 27 October 2008

Automating tasks in Linux

In Linux, the "crontab" command can be used to schedule tasks. Unlike Windows, it provides a command-based interface, rather than a graphical interface, but it can be configured extremely quickly and comes with a set of very useful options. To see all options, type "man crontab" into a terminal window. To add a new "cron job", simply enter the following into a terminal:

crontab -e

Let's look at a typical example. Say I want to want to run a subversion (SVN) backup script at 3am every Tuesday, and I want to write all output (including errors) to a logfile. I would add the following cron job:

0 3 * * 2 /home/username/backup/svn_backup.sh >/tmp/svn_backup_log.out 2>&1

Let's break down the above command:

  • 0 3 * * 2
    • The first part of all cron commands is the same, containing 5 fields: (1) minute(0-59) (2) hour(0-23) (3) day_of_month(0-31) (4) month(1-12) (5) day_of_week(0-7 | where Sunday is 0 or 7)
    • To ignore any field, simply use an asterisk for that field ('*')
  • /home/username/backup/svn_backup.sh
    • This is the script to run
  • >/tmp/svn_backup_log.out
    • Tells cron where to write any standard output from the script (will be overwritten at each run)
  • 2>&1
    • Tells cron to write any errors to the same place as standard output
This simple setup allows you to run a script, then view it's output to ascertain whether everything went OK. You can also configure cron to email you if any errors occured - a good explanation of this can be found here.

If you are curious about the svn backup script, let me know and I will write it up in a future post.

No comments: