Is this the last day of the month?

Is this the last day of the month?

Often, you want to figure out if today is the last day of the month. This is an oddly difficult problem...between months having different numbers of days, leap years, and the occasional canceled leap day, calendar math is difficult.

Fortunately, this is kinda a "Solved Problem". Most unix systems have a command, "cal", which will print a calendar of the current month (it does other things, too). The very last thing the cal command prints before exiting is the last day of the current month. so... run cal, grab the last thing it puts out, and compare it to today's date.

$ cal
    October 2020
Su Mo Tu We Th Fr Sa
             1  2  3
 4  5  6  7  8  9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31

$ set $(cal)
$ shift $(($# - 1))
$ echo $1
Compare that to the output of:
$ date "+%d" 
and you know if today is the last day of the month.

"set $(cal)" causes cal to be run, and its output expanded to the shell "parameter variables" -- $1, $2, etc., as if they were entered on the command line of a script. So in our case, $1="October", $2="2020", $3="Su", etc. We want the very last thing it put out. $# is the number of "parameters" entered. We want the very last parameter, so we use the "shift" command to remove all but one less than the number of variables. When that's done, $1 will be the last thing run through the "set" command.

If you have ksh93, you can use it's internal date manipulation as detailed here.

Holland Consulting home page
Contact Holland Consulting

since June 24, 2020

Copyright 2020, Nick Holland, Holland Consulting