0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Write Cron Expression in Bash: Syntax and Examples

A cron expression in bash is a string with five fields representing minute, hour, day of month, month, and day of week, followed by the command to run. Use the format minute hour day_of_month month day_of_week command in your crontab to schedule tasks.
📐

Syntax

A cron expression has five time fields followed by the command to execute. Each field controls when the command runs:

  • Minute: 0-59
  • Hour: 0-23
  • Day of Month: 1-31
  • Month: 1-12
  • Day of Week: 0-7 (0 or 7 is Sunday)

Use * to mean "every" value in that field.

bash
* * * * * /path/to/command
💻

Example

This example runs a script every day at 2:30 AM. It shows how to write the cron expression and the command to execute.

bash
30 2 * * * /home/user/backup.sh
Output
No direct output; the script /home/user/backup.sh runs daily at 2:30 AM
⚠️

Common Pitfalls

Common mistakes include:

  • Using incorrect ranges (e.g., hour > 23)
  • Forgetting that day of week 0 and 7 both mean Sunday
  • Not specifying the full path to commands or scripts
  • Not setting environment variables needed by the script

Always test your cron jobs and check logs for errors.

bash
# Wrong: 60 24 * * * /path/to/script.sh
# Right: 0 0 * * * /path/to/script.sh
📊

Quick Reference

FieldAllowed ValuesDescription
Minute0-59Minute of the hour
Hour0-23Hour of the day
Day of Month1-31Day of the month
Month1-12Month of the year
Day of Week0-7Day of the week (0 or 7 = Sunday)

Key Takeaways

A cron expression has five time fields followed by the command to run.
Use * to represent all possible values in a field.
Always specify full paths in cron commands to avoid errors.
Check your cron syntax carefully to avoid invalid schedules.
Test cron jobs and monitor logs to ensure they run as expected.