Learn the UNIX/Linux command line

Number of days in a given month

Chris F.A. Johnson describes in this Tuesday tip how to find the number of days in a given month. Chris is a UNIX genius, but I think there is a much easier way. Why not use the cal command? Its available on every System I have tried to use. AIX, Solaris, and many different flavors of Linux:

January:

[email protected]:~ # cal 1 `date +%Y` | egrep -v '[A-Za-z]' | wc -w
31

February:

[email protected]:~ # cal 2 `date +%Y` | egrep -v '[A-Za-z]' | wc -w
28

The following is equivalent (and much simpler) to Chris’s:

days_in_month() { ## USAGE: days_in_month [month [year]]
if [ -n "$1" ]
then
dim_m=$1
dim_y=$2
else
eval `date "+dim_m=%m dim_y=%Y"`
fi
_DAYS_IN_MONTH=`cal $dim_m $dim_y | egrep -v '[A-Za-z]' | wc -w`
}

I prefer a different method of programming. If the function echos the result, it can be assigned to a variable like so, days=$( days_in_month ). The following function is how I would write it:

days_in_month() { ## USAGE: days_in_month [month [year]]
if [ -n "$1" ]
then
dim_m=$1
dim_y=$2
else
eval `date "+dim_m=%m dim_y=%Y"`
fi
echo `cal $dim_m $dim_y | egrep -v '[A-Za-z]' | wc -w`
}

The reason I prefer this method is that I do not like setting variables and then using the variable name after running the function. There are alot of reasons, not the least of which is that you have remember both the function name and the variable(s) that it sets. Much too complicated for me.