Calendar in linux shell programming problems

I want my calendar to correctly handle months with leading zeros for example: "cal 01" or "cal 01 2012"

How do I write the code to make my calendar to correctly handle months with leading zeros?

This is my code so far:

$ cat cal
#cal: nicer interface to /usr/bin/cal

case $# in
0)  set 'data';m=$2; y=$6 ;;    # no argu: use today
1)  m=$1; set 'data'; y=$6 ;;   # 1 rg: use this year
*)  m=$1; y=$2 ;;           # 2 ags: month and year 

case $m in
jan*|Jan*)  m=1 ;;
feb*|Feb*)  m=2 ;;
mar*|Mar*)  m=3 ;;
apr*|Apr*)  m=4 ;;
may*|May*)  m=5 ;;
jun*|Jun*)  m=6 ;;
jul*|Jul*)  m=7 ;;
aug*|Aug*)  m=8 ;;
sep*|Sep*)  m=9 ;;
oct*|Oct*)  m=10 ;;
nov*|Nov*)  m=11 ;;
dec*|Dec*)  m=12 ;;
[1-9]|10|11|12) ;;          # numeric month
*)      y=$m; m="" ;;       # plain year

/usr/bin/cal $m $y          # run the real one


You can do multiple regex matching in your case statement, i.e.

case $m in
01|1|jan*|Jan*)  m=1 ;;
02|2|feb*|Feb*)  m=2 ;;


Else, you could use shell parameter substitution to remove any leading 0's, i.e.

# as a way to demonstrate param sub on $1 etc, load values to $1 and $2
set -- 01 02 
echo ${1#0}
echo ${2#0}

# output


For your follow-up question

Example, the current month is November, 2005, if you run "cal 01", you should print out the calendar of Jan. 2006

Try this:

# if the month input is less than the current month, assume the next year
if (( ${y:-0} == 0  && m < $(/bin/date +%m) )) ; then
   y=$(/bin/date +%Y)

${y:-0} is one of several parameter checking syntaxs provided by most shells that allows a default value to be substituted if the var value is completely unset (not set at all) or = "". So in this case, if y wasn't set by the command line, it will appear as 0 in this evaluation, allowing the && section to be be executed to test the month, etc.

You'll need to extend your case $# processing to allow for 1 argument, that is assumed to be a month value.

I hope this helps.

Need Your Help

Conditionally replacing values in SELECT

sql sql-server

I've got a query that returns the cost of wages for a given member of staff

How read in Delphi the domain connected user on a web application

multithreading delphi web user

An application must read the domain user connected for to do something.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.