Today I was writing a shell script that performs different actions depending on the day of the month. Nothing fancy but then I came across an interesting issue, which is how to get number of days in a month. I got interested and started playing with shell commands, namely cal and awk utilities.

Solution is very simple as to get number of days for current month (March 2013) you need to execute commands:

$ cal $(date +"%m %Y") | awk 'NF {DAYS = $NF}; END {print DAYS}'

Now you can extend the idea to a more descriptive form:

$ cal $(date +"%m %Y") | awk 'NR==1 {MON_YEAR=$1 " " $2};NF {DAYS = $NF}; END {print MON_YEAR " - " DAYS}'
March 2013 - 31

Quickly get number of days in the next month (April 2013):

$ cal $(date +"%m %Y" --date "next month") | awk 'NF {DAYS = $NF}; END {print DAYS}'

Alternatively simplify it a bit:

$ cal 4 2013 | awk 'NF {DAYS = $NF}; END {print DAYS}'

As you can see you don’t need anything more than basic shell commands to determine number of days in a month.