Cron – Does 31 necessarily imply the end of the month in a cron job

cron

For cron job we know we can set time as below.

# +------------ Minute (0 - 59)
# | +---------- Hour (0 - 23)
# | | +-------- Day of the Month (1 - 31)
# | | | +------ Month (1 - 12)
# | | | | +---- Day of the Week (0 - 7) (Sunday is 0 or 7)
# | | | | |
# * * * * * command

What I want to know is that when we set day of the month 31, does this means the end of each month though the month does not have day 31.

Best Answer

No, 31 means 31.

However, you can do some trickery. Set the job to run on any day which could potentially be the last day of the month (ie 28-31 in the day-of-month field), and then replace your command with a shell expression comprising a test on the date guarding the command:

0 0 28-31 * * [ "`date +%m`" != "`date --date=tomorrow +%m`" ] && command

The expression inside the test brackets just asks if the month number today is different to the month number tomorrow, which of course will only be true on the last day of the month. Note that the form of this expression depends on your local date - you may need to tweak it if you don't have the current GNU version.

I should say that I didn't invent this - I found it with a quick Google in a mailing list post by a Matthew Jarvis. I would imagine this is very much a standard old Unix wizard's trick, though.