Structure of a crontab
Entry
Each entry in a crontab
file is made up of two main parts:
Schedule specification: Defines when the job should run.
Command to execute: Specifies the script, command, or executable to run.
Basic Syntax
bashCopy code* * * * * command_to_execute
Field | Value Range | Description |
Minute | 0-59 | The minute when the task runs. |
Hour | 0-23 | The hour of the day (24-hour format). |
Day of Month | 1-31 | The day of the month. |
Month | 1-12 | The month of the year. |
Day of Week | 0-6 (0 = Sunday) | The day of the week. |
Special Characters in crontab
Fields
Character | Usage |
* | Matches every value in the field. |
, | Separates multiple values. |
- | Specifies a range of values. |
/ | Specifies step values (increments). |
Examples with *
and Other Characters
Run every minute
bashCopy code* * * * * /path/to/script.sh
- Runs the command every minute of every hour, every day.
Run at 5 AM daily
bashCopy code0 5 * * * /path/to/script.sh
- Runs the command at exactly 5:00 AM.
Run on the 1st of every month at midnight
bashCopy code0 0 1 * * /path/to/script.sh
- Executes at midnight on the first day of each month.
Run every Sunday at 2 PM
bashCopy code0 14 * * 0 /path/to/script.sh
- Executes at 2:00 PM every Sunday.
Run every 5 minutes
bashCopy code*/5 * * * * /path/to/script.sh
- Executes every 5 minutes.
Run every hour between 9 AM and 5 PM
bashCopy code0 9-17 * * * /path/to/script.sh
- Executes at the start of every hour from 9 AM to 5 PM.
Run on weekdays (Monday to Friday) at 10:30 PM
bashCopy code30 22 * * 1-5 /path/to/script.sh
- Executes at 10:30 PM Monday through Friday.
Run on the 15th and 30th of every month at noon
bashCopy code0 12 15,30 * * /path/to/script.sh
- Executes at 12:00 PM on the 15th and 30th of each month.
Special Macros in crontab
Macro | Equivalent Schedule | Description |
@reboot | Runs once at system startup. | Example: Start a service on reboot. |
@yearly | 0 0 1 1 * | Runs once a year (midnight, Jan 1). |
@monthly | 0 0 1 * * | Runs once a month (midnight, 1st day). |
@weekly | 0 0 * * 0 | Runs once a week (midnight, Sunday). |
@daily | 0 0 * * * | Runs once a day (midnight). |
@hourly | 0 * * * * | Runs every hour. |
Common Issues and Troubleshooting
cron
Job Not RunningEnsure the script has execution permissions:
bashCopy codechmod +x /path/to/script.sh
Check the cron logs:
bashCopy codegrep CRON /var/log/syslog
Environment Variables
cron
may not have access to your user's environment variables. Explicitly set paths or source environment files in your script.
Output Redirection
Redirect output to capture logs or silence errors:
bashCopy code* * * * * /path/to/script.sh >> /path/to/logfile.log 2>&1