Home / Linux / CRONTAB Basics

CRONTAB Basics

A crontab file has six fields:
       Minute 0-59
       Hour 0-23
       Day of month 1-31
       Month 1 – 12
       Day of Week 0 – 6, with 0 = Sunday
       Unix Command or Shell Scripts
    • To edit a crontab file, type:

Crontab -e

 

    • To view a crontab file, type:

Crontab -l

0  4 * * 5       /dba/admin/analyze_table.ksh
30 3  * * 4,6    /dba/admin/hotbackup.ksh /dev/null 2>&1

 

In this example, the first entry shows the analyze table script  runs every Friday at 4:00 a.m. The second entry shows that  a  hot backup script runs every Tuesday and Saturday at 3:00 a.m.

What if you’d want to run something every 10 minutes? Well you could do this:

1
0,10,20,30,40,50 * * * * /bin/execute/this/script.sh

But crontab allows you to do this as well:

1
*/10 * * * * /bin/execute/this/script.sh

Which will do exactly the same.

Special words

For the first (minute) field, you can also put in a keyword instead of a number:

1
2
3
4
5
6
7
8
@reboot     Run once, at startup
@yearly     Run once  a year     "0 0 1 1 *"
@annually   (same as  @yearly)
@monthly    Run once  a month    "0 0 1 * *"
@weekly     Run once  a week     "0 0 * * 0"
@daily      Run once  a day      "0 0 * * *"
@midnight   (same as  @daily)
@hourly     Run once  an hour    "0 * * * *"

Leaving the rest of the fields empty, this would be valid:

1
@daily /bin/execute/this/script.sh

Storing the crontab output

By default cron saves the output of /bin/execute/this/script.sh in the user’s mailbox (root in this case). But it’s prettier if the output is saved in a separate logfile. Here’s how:

1
*/10 * * * * /bin/execute/this/script.sh >> /var/log/script_output.log 2>&1

Explained

Linux can report on different levels. There’s standard output (STDOUT) and standard errors (STDERR). STDOUT is marked 1, STDERR is marked 2. So the following statement tells Linux to store STDERR in STDOUT as well, creating one datastream for messages & errors:

1
2>&1

Now that we have 1 output stream, we can pour it into a file. Where > will overwrite the file, >>will append to the file. In this case we’d like to to append:

1
>> /var/log/script_output.log

Check Also

Install miniDLNA server on your Zyxel server.

miniDLNA has some advantages over the default media server Twonky. Most important you will be …

Leave a Reply