Nerd Tech Talk

Using Crontab


Crontab command is used to edit crontab files. These files have a list of commands that are to be executed on a particular day at a given time. They are most useful when you want to run some tests or some cleanup commands or something that needs to be run regularly – say weekly or monthly. The commands specified are executed automatically and logs can also be collected from those commands, along with an email that will be sent to the user. I had not used this feature until recently when I was asked to use them at my job. These crontab files are maintained per user, so each user can configure his own commands to be run.

Make sure your username is not present in /usr/lib/cron/cron.deny file before you try to use crontab.


crontab [-u user] [-l | -r | -e] [-i] [-s]
$ crontab -e /* to edit crontab file in vi editor */


Minutes(0-59) Hour(0-23) Day_of_month(1-31) Month(1-12) Day_of_week(0-6) Command_to_run

10            01         *                  *                   6                ls /home/ash > /home/ash/ls.log 2>&1

$ crontab -l (OR) $ crontab -l ash /* list contents of crontab
                                        file (for a user) */
10 01 * * 6 ls /home/ash > /home/ash/ls.log 2>&1

=> Run the command – “ls /home/ash > /home/ash/ls.log” on every Sunday at 01:10 hours every month

The time and date fields are:

	      field	     allowed values
	      -----	     --------------
	      minute	     0-59
	      hour	     0-23
	      day of month   1-31
	      month	     1-12 (or names, see below)
	      day of week    0-7 (0 or 7 is Sun, or use names)
A field may be an asterisk (*), which always stands for "first-last".

Adding more entries to crontab:

$ crontab -e
$ crontab -l
10 01 * * 6 ls /home/ash > /home/ash/ls.log 2>&1
00 21 * 1,8,11 * /bin/bash /home/ash/bin/build1 >/home/ash/logs/test1.log 2>&1
00 23 * * 0-5 ssh ash-linux /home/ash/bin/ >>/home/ash/logs/test2.log 2>&1

Delete Crontab:

$ crontab -r         /* delete crontab */
$ crontab -ri       /* Prompts the user before deleting crontab */
crontab: really delete ash's crontab? y

$ crontab -l
no crontab for ash