Linux – how to combine day of week and day of month in crontab

cronlinux

I want to run some jobs on day 1 of each month and others on day 1 of each week, but what if both collide? In this case the month should have precedence. How do I tell this cron?

# run on every day 1 of each month:
59 12 1 * * user script_month

# run on every day 1 of each week:
59 12 * * 1 user script_week

EDIT 1:

There is an answer that uses "IF" which is a good workaround.

What about this:

# run on every day 1 of each week:
59 12 2-31 * 1 user script_week

Maybe it also does what I am asking for? (run on all weeks on day 1 except if it is day 1 of the month)

Edit 2:

I found this:

"If both [date] fields are restricted (i.e., aren't *), the command will be run when either field matches the current time." (source: http://thewatertower.org.uk/news/000160/crontab_the_first_five_fields_combine_to_restrict_the_schedule_except_for_when_they_dont.html )

Seems it is not possible like I wrote in Edit 1?

Best Answer

Have script_week check whether it is running on day 1 of the month. If it is, then have it exit before doing any real work. For example, in a bash script, such a check might look like this:

if [ `/bin/date +%d` = "01" ]; then exit 0; fi

If you prefer, you could leave script_week unmodified, and instead put a similar check into the crontab entry for script_week, something like this:

59 12 * * 1 user if [ `/bin/date +\%d` != "01" ]; then script_week; fi
Related Topic