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
esac
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
esac
/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
1
2
Edit
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++))
fi
${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.