2010/03/29

Is today the last $weekday of the month?

Classic problem in sysadmin: How to run a script on the last Sunday (or whatever day) of the month. This snippet is correct for all days, even in leap years between 1904 and 2096, inclusive. It messes up on February 22 each century, except when the year is divisible by 400 (works in 1600, 2000, 2400, etc. but breaks in 2100, 2200, 2300) But I'll be retired by then...

My answer, in Korn Shell:


# Day of the week to run on:
DOW=Sunday

OLDLC_TIME=$LC_TIME
export LC_TIME=C
# Requires /usr/bin/ksh to run correctly.
# I couldn't be bothered to get the expr quoting and backquoting working in /bin/sh
case `date +%b` in
Jan|Mar|May|Jul|Aug|Oct|Dec) D=31;;
Apr|Jun|Sep|Nov) D=30;;
Feb) D=$(( 28 + ( $(date +%Y) %4 == 0 ));;
# FIXME: Y2.1K bug here.
esac

if [[ `date +%A` == "$DOW" ]] && [[ $(( $(date +%e) + 7 -gt $D ]]
# then next Sunday is after the end of this month, so today's the last Sunday of this month
then
....
fi

LC_TIME=$OLDLC_TIME

No comments: