Getting a cron to execute on the last day of month

Tags:

It had never occured to me before, but suddenly I had the need to run a script on the last day of every month, in order to get the right results per month.

Given that a month's last date can be 28, 29 30 or 31, it wasn't as simple as usual!

After a bit of googling I found the easy solution. Simply get the crontab to run every day, but add into the crontab a check to see if tomorrow's date of the month is '01'. If it isn't, do nothing. If it is, then continue with the rest of the script.

36 14 * * * [ `date -d tomorrow +%d` -eq '01'] && /execute/the/real/script.sh

Edit: Hmm, got a syntax error there:

/bin/sh: -c: line 0: unexpected EOF while looking for matching ``' /bin/sh: -c: line 1: syntax error: unexpected end of file

Ah well, since I'm only executing a shell script, I just added this to my script:

#!/bin/bash
TODAY=`/bin/date +%d`
TOMORROW=`/bin/date +%d -d "1 day"`
# See if tomorrow's day is less than today's
if [ $TOMORROW -lt $TODAY ]; then
(real script executes here)
exit 0
fi
exit 1