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

Solution 1:

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.

Solution 2:

No, I think the best you can do is run at midnight on the 1st of the month, or set up individual crontab lines for each month (or at least, a line for months with 28,29,30 and 31 days)

0 0 28,29 2               * /my/command
0 0 30    4,6,9,11        * /my/command
0 0 31    1,3,5,7,8,10,12 * /my/command