A crontab entry specifies the time to execute a command and the command to be executed. Each line in the cron table defines a single command. The command can either be a script or a binary application. When cron runs a task, it runs as the user who created the entry, but it does not source the user's .bashrc. If the task requires environment variables, they must be defined in the crontab.
Each cron table line consists of six space-delimited fields in the following order:
- Minute (0 - 59)
- Hour (0 - 23)
- Day (1 - 31)
- Month (1 - 12)
- Weekday (0 - 6)
- COMMAND (the script or command to be executed at the specified time)
The first five fields specify the time when an instance of the command is to be executed. Multiple values are delimited by commas (no spaces). A star signifies that any time or any day will match. A division sign schedules the event to trigger every /Y interval (*/5 in minutes means every five minutes).
- Execute the test.sh script at the 2nd minute of all hours on all days:
02 * * * * /home/slynux/test.sh
- Execute test.sh on the 5th, 6th, and 7th hours on all days:
00 5,6,7 * * /home/slynux/test.sh
- Execute script.sh every other hour on Sundays:
00 */2 * * 0 /home/slynux/script.sh
- Shut down the computer at 2 a.m. every day:
00 02 * * * /sbin/shutdown -h
- The crontab command can be used interactively or with prewritten files.
Use the -e option with crontab to edit the cron table:
$ crontab -e
02 02 * * * /home/slynux/script.sh
When crontab -e is entered, the default text editor (usually vi) is opened and the user can type the cron jobs and save them. The cron jobs will be scheduled and executed at specified time intervals.
- The crontab command can be invoked from a script to replace the current crontab with a new one. Here's how you do this:
- Create a text file (for example, task.cron) with the cron job in it and then run crontab with this filename as the command argument:
$ crontab task.cron
- Alternatively, specify the cron job as an inline function without creating a separate file. For example, refer to the following:
$ crontab<<EOF
02 * * * * /home/slynux/script.sh
EOF
The cron job needs to be written between crontab<<EOF and EOF.