Skip to content

Quick and dirty Crontab tutorial

For those who have used Linux for any length of time the issue of automating tasks will have come up. The time honoured way of doing this is through Cron. Each user on a Linux system has a crontab – a list of commands that is run at a predetermined time.

I’m not going into massive detail into what Cron is and how it works – the MAN page is a good start for that. However in order to automate tasks you need to put them into your crontab, and here is how you do that.

1. Type ‘crontab -e‘ into the shell prompt. This will let you edit the crontab file, on some distributions (CentOS, Fedora) the editor will be Vi (or Vim) or in case of Debian and Ubuntu (and maybe others) it is nano.
2. Enter the timing and command – use must you absolute pathnames for everything.
The way crontab files are formatted is something like this:

*1  *2  *3  *4  *5 <command>

*1 = minute of the hour (0 – 59)
*2 = hour of the day (24 hour clock, 0 – 24)
*3 = week of the month (0 – 52)
*4 = month of the year (0 – 12 where January = 0)
*5 = day of the week (0 – 7 where Sunday = 0)
<command> = command using absolute paths

So for example if I wanted to run /home/crapple/ every Monday at 1am I would put the following in the crontab:

* 1 * * 1 /home/crapple/

Basically * means every minute during 1am on Monday, so the script will run 60 times. If you want it to run only once, pick a minute and change the first * to a number between 0 and 59.

Once you have entered the command you wish to run, save the file and quit – so in Vi/Vim, escape edit mode and :wq as normal or in nano ctrl+o then ctrl+x.

And you’re done. Just remember if your script outputs to STDOUT then when it runs the output will be placed in your user account’s email. This can be suppressed by putting > /dev/null at the end of your command, so using our previous example:

* 1 * * 1 /home/crapple/ > /dev/null

Now all input will be sent to /dev/null.

One final thing, if you want to comment your crontab file to make it understandable at a later date, single line comments start with a #, for example

* 1 * * 1 /home/crapple/ > /dev/null # this is a comment

Happy automation!