Hack 74. Crontab Basic Guide

by Ramesh

Using cron you can execute a shell-script or Linux commands at a specific time and date. For example a sysadmin can schedule a backup job that can run every day.

How to add a job to the cron?

  1. # crontab –e
  2. 0 5 * * * /root/bin/backup.sh

This will execute /root/bin/backup.sh at 5 a.m every day.

Description of Cron fields.

Following is the format of the crontab file.

  1. {minute} {hour} {day-of-month} {month} {day-of-week} {full-path-to-shell-script}
  • minute: Allowed range 0 – 59
  • hour: Allowed range 0 – 23
  • day-of-month: Allowed range 0 – 31
  • month: Allowed range 1 – 12. 1 = January. 12 = December.
  • Day-of-week: Allowed range 0 – 7. Sunday is either 0 or 7.

Crontab examples

1. Run at 12:01 a.m. 1 minute after midnight everyday.

This is a good time to run backup when the system is not under load.

  1. 1 0 * * * /root/bin/backup.sh

2. Run backup every weekday (Mon – Fri) at 11:59 p.m.

  1. 59 11 * * 1,2,3,4,5 /root/bin/backup.sh

Following will also do the same.

  1. 59 11 * * 1-5 /root/bin/backup.sh

3. Execute the command every 5 minutes.

  1. */5 * * * * /root/bin/check-status.sh

4. Execute at 1:10 p.m on 1st of every month

  1. 10 13 1 * * /root/bin/full-backup.sh

5. Execute 11 p.m on weekdays.

  1. 0 23 * * 1-5 /root/bin/incremental-backup.sh

Crontab Options

Following are the available options with crontab:

  • crontab –e : Edit the crontab file. This will create a crontab, if it doesn’t exist
  • crontab –l : Display the crontab file.
  • crontab -r : Remove the crontab file.
  • crontab -ir : This will prompt user before deleting a crontab.