Schedule cron Job on First Sunday of the Month

When you need to schedule a Unix or Linux job in crontab to run on the first Sunday of the month, or any other weekday for that matter, your first instinct may be to write your cron entry to look like this:

0 22 1-7 * 0 /home/user/myscript.sh

However, you will find that the job will be executed every day for the first 7 days of the month, as well as each Sunday thereafter. The following paragraph from the crontab man page explains it all.

The day of a command’s execution can be specified by two fields — day of month, and day of week. If both fields are restricted, the command will be run when either field matches the current time.

By adding a weekday check in the command section of your cron entry, you can create a condition to execute your job if the cron entry is executed on the desired weekday, in this case Sunday:

0 22 1-7 * * [ "$(date '+\%a')" == "Sun" ] && /home/user/myscript.sh

Leave a Reply

Your email address will not be published. Required fields are marked *

*