Find out last day of month using “cal” on Unix

I was writing a script the other day that required having to find out the last day of a month in a future month again generated by the script. I searched online for solutions but most of them were based on the “date” commands math functions. However, GNU date wasn’t available on the solaris machine I was using so I was stuck with the “cal” command.


After trying a “cal” based solution online and realizing it wouldn’t work for half the year, I gave up and proceeded to try something on my own. And I came up with this:

`cal $x $y | tr -d '\n' | awk '{print substr($0,length-1,2)}'`

What this does is to generate the calendar for month “x” in year “y”, then remove all new line characters so the entire data lines up on one single line with the last date of the month obviously at the end. I then used “awk” to cut 2 characters at n-1 and n.



So far I’ve not had any trouble with this script. But. if you happen to find a bug in this, please do let me know.

This entry was posted in Linux, Tech. and tagged , , , , , . Bookmark the permalink.

6 Responses to Find out last day of month using “cal” on Unix

  1. Very neat, thanks a lot ;)

  2. RNG says:

    cal 2 2012 | tr -d ‘\n’ | awk ‘{print substr($0,length-1,2)}’
    errors out by returning no output.

    Why not
    cal 2 2012 | tr -d ‘\n’ | awk ‘{print $NF}’
    which is more “awk-ish” anyway?

    Even more straight-forward – to achieve the same goal:

    date -d “20120201 + 1 month – 1 day” +%d

    to get the last day of Feb 2012. Purposely I picked a leap year.

    It’s easy to generalize to get it working for %yyyy%mm.

    • RNG says:

      Oops – I missed you said ‘Solaris’. I believe it’s worth installing GNU tools on Solaris, as life becomes so much easier :-)

  3. Riyaz says:

    I found an easier way to do the same…
    cal $x $y | tail -2 | tr ‘ ‘ ‘\n’ | tail -2

  4. Hi:
    I solved on this way
    cal | tr ” ” “\n” | grep . | tail -1

    Sorry I did not see the solution of Riyaz, but works too


  5. Isaac Marcos says:

    This seems simpler:

    a=( $(cal $x $y) ); echo “${a[-1]}”


    echo $(cal $x $y) | awk ‘{print $NF}’

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s