Today is about deciding whether the date entered is correct, and using the function in the example 03 before us
is code
#!/bin/sh # valid-date-Validates a date, taking into account leap year rules. Exceedsdaysinmonth () {Case $ (echo $1|tr ' [: Upper:] ' [: Lower:] ') in jan*) days=31;;
feb*) days=28;; mar*) days=31;;
apr*) days=30;; may*) days=31;;
jun*) days=30;; jul*) days=31;;
aug*) days=31;; sep*) days=30;;
oct*) days=31;; nov*) days=30;;
dec*) days=31;; *) echo "$0:unknown month name $" >&2; Exit 1 Esac If [$2-lt 1-o $2-gt $days]; Then return 1 else return 0 # The day number is valid fi} isleapyear () {year=$1 if [' $ ((year% 4)]-ne 0]; Then return 1 # Nope, not a leap year elif ["$ (year%)]"-eq 0]; Then return 0 # Yes, it's a leap year Elif ["$ ((year%))"-eq 0]; Then return 1 else return 0 fi} # # Begin main script if [$#-ne 3]; Then echo "Usage: $ month Day" >&2 echo "typical input formats are 8 3 2002" >&2 exit 1 Fi # Norma Lize Date and split BACK out returned values if [$?-eq 1]; Then exit 1 # error condition already reported by Normdate Fi Monthnotoname () {# Sets the variable ' month ' to ' a Ppropriate value Case "01|1" monthd= ";;
02|2) monthd= "Feb";; 03|3) monthd= "Mar";;
04|4) monthd= "APR";; 05|5) monthd= "may";;
06|6) monthd= "June";; 07|7) monthd= "June";;
08|8) monthd= "Aug";; 09|9) monthd= "Sep";;
Monthd= "OCT";; Monthd= "Nov";;
Monthd= "Dec";; *) echo "$0:unknown numeric month value $ >&2;" Exit 1 ESAC return 0} monthnotoname $ month= "$MONTHD" day= "$" year= "$" if! Exceedsdaysinmonth $month "$"; Then if ["$month" = "Feb"-a "$"-eq "29"]; Then if! Isleapyear $; Then echo "$: not" a leap year, so Feb doesn ' t have ">&2 exit 1 fi else echo" $0:bad Day Value: $month doesn ' t have $ ">&2 Exit 1 fi fi echo" Valid Date: $newdate "Exit 0
Analysis:
1 The first is to determine whether the number of parameters entered by the user is correct, and then the case is in the statement to determine whether the month is reasonable.
2 The Monthnotoname function appears before our No. 03 scripting case, the numeric date used to convert the input is a string.
3) Exceedsdaysinmonth is used to determine whether days exceed the maximum number of days of the corresponding month, followed by if ["$month" = "Feb"-a "$"-eq "29"]; Then if! Isleapyear $; Then used to judge the special situation of leap year February
4 The overall feeling is that the script is still very compact, especially in judging the relationship between leap years and February, a little bit of meaning.