#!/bin/bash # valid-date--Validates a date, taking into account leap year rules. setglobal PATH = ".:$PATH" proc exceedsDaysInMonth { # Given a month name and day number in that month, this function will # return 0 if the specified day value is less than or equal to the # max days in the month; 1 otherwise. match $[echo $1|tr '[:upper:]' '[:lower:]] { with jan* setglobal days = '31' with feb* setglobal days = '28' with mar* setglobal days = '31' with apr* setglobal days = '30' with may* setglobal days = '31' with jun* setglobal days = '30' with jul* setglobal days = '31' with aug* setglobal days = '31' with sep* setglobal days = '30' with oct* setglobal days = '31' with nov* setglobal days = '30' with dec* setglobal days = '31' with * echo "$0: Unknown month name $1" > !2; exit 1 } if test $2 -lt 1 -o $2 -gt $days { return 1 } else { return 0 # the day number is valid } } proc isLeapYear { # This function returns 0 if the specified year is a leap year; # 1 otherwise. # The formula for checking whether a year is a leap year is: # 1. Years not divisible by 4 are not leap years. # 2. Years divisible by 4 and by 400 are leap years. # 3. Years divisible by 4, not divisible by 400, and divisible by # 100, are not leap years. # 4. All other years divisible by 4 are leap years. setglobal year = $1 if test "$shExpr('year % 4')" -ne 0 { return 1 # nope, not a leap year } elif test "$shExpr('year % 400')" -eq 0 { return 0 # yes, it's a leap year } elif test "$shExpr('year % 100')" -eq 0 { return 1 } else { return 0 } } # BEGIN MAIN SCRIPT # ================= #if [ $# -ne 3 ] ; then # echo "Usage: $0 month day year" >&2 # echo "Typical input formats are August 3 1962 and 8 3 2002" >&2 # exit 1 #fi # Normalize date and store the return value to check for errors. #newdate="$(normdate "$@")" #echo $newdate #if [ $? -eq 1 ] ; then # exit 1 # Error condition already reported by normdate #fi # Split the normalized date format, where # first word = month, second word = day, third word = year. #month="$(echo $newdate | cut -d\ -f1)" #day="$(echo $newdate | cut -d\ -f2)" #year="$(echo $newdate | cut -d\ -f3)" # Now that we have a normalized date, let's check to see if the # day value is legal and valid (e.g., not Jan 36). #if ! exceedsDaysInMonth $month "$2" ; then # if [ "$month" = "Feb" -a "$2" -eq "29" ] ; then # if ! isLeapYear $3 ; then # echo "$0: $3 is not a leap year, so Feb doesn't have 29 days" >&2 # exit 1 # fi # else # echo "$0: bad day value: $month doesn't have $2 days" >&2 # exit 1 # fi #fi #echo "Valid date: $newdate" #exit 0