Linux, improved cal, shell programming
I am working with cal for a homework assignment and i am stuck on one point.
It is unlikely that anyone is really interested in getting a gregorian calendar for a year in the first century, a time when the gregorian calendar didn't even exist. Use the "windowing" strategy to allow your new cal to handle years that are not the full 4 digit year. If the year is in the range of 0 <= year <= 50, assume the year is really 2000-2050. If the year is in the range 51 <= year <= 99, assume the year is really 1951-1999.
file named improvedcal.sh call the shell with sh improvedcal.sh 1 2011 for example code
case $# in # rando stuff *) m=$1; y=$2 ; # 2 ags: month and year if ((y >= 0 && y <= 50)); then y+=2000 elif ((y >= 51 && y <= 99)); then y+=1900 fi;; 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 0[1-9]|010|011|012) ;; # numeric month # *) y=$m; m="" ;; # plain year esac /usr/bin/cal $m $y # run cal with new inputs
But this is not working for some reason does anyone have any pointers for me? It just skips right over this part for some reason.
Try running your script with bash -xv, it will help you understand what is happening.
Read also Bash programming intro
If you don't declare a variable and directly assign to it, then it's either a string (var=stuff) or an array (var=(element0 element1 element2)). Since y is a string, y+=2000 appends the string 2000 to the value.
You can declare y as an integer variable, then the += operator will perform an addition.
declare -i y=$2 if ((y >= 0 && y <= 50)); then y+=2000 elif ((y >= 51 && y <= 99)); then y+=1900 fi
Another way is to use the += operator inside an arithmetic expression:
y=$2 if ((y >= 0 && y <= 50)); then ((y+=2000)) elif ((y >= 51 && y <= 99)); then ((y+=1900)) fi
Or you can perform the arithmetic operation and assign the result:
y=$2 if ((y >= 0 && y <= 50)); then y=$((y+2000)) elif ((y >= 51 && y <= 99)); then y=$((y+1900)) fi
You can write all of this in a single arithmetic expression using the ? … : conditional operator:
y=$2 if ((y >= 0)); then ((y <= 50 ? y += 2000 : y <= 99 ? y+=1900 : 0)); fi