驗證日期是否有效,主要考慮閏年的情況,閏年的2月份有29天
閏年規則:
1、普通閏年:公曆年份是4的倍數的,且不是100的倍數,爲普通閏年。(如2004年就是閏年)
2、世紀閏年:公曆年份是整百數的,必須是400的倍數纔是世紀閏年(如1900年不是世紀閏年,2000年是世紀閏年)
本案例用將會調用到 003#規範日期格式。
腳本:
#!/usr/bin/env bash # valid-date # 同目錄存在normdate,用於規範化日期,後面將會調用到 # 參考003#規範日期格式 PATH=.:$PATH # 判斷給定月份的有效天數 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: Unkown month name $1" >&2 exit 1 esac # 判斷天數是否有效,有效返回0,無效返回1 if [ $2 -lt 1 -o $2 -gt $days ]; then return 1 else return 0 fi } # 驗證閏年 isLeapYear() { year=$1 if [ "$((year%4))" -eq 0 -a "$((year%100))" -ne 0 ]; then return 0 elif [ "$((year%400))" -eq 0 ]; then return 0 else return 1 fi # if [ "$((year % 4))" -ne 0 ]; then # return 1 # elif [ "$((year % 400))" -eq 0 ]; then # return 0 # elif [ "$((year % 100))" -eq 0 ]; then # return 1 # else # return 0 # fi } # main usage="Usage: $0 month day year\nTypical input formats are August 3 2019 and 8 3 2019" if [ $# -ne 3 ]; then echo -e "$usage" >&2 exit 1 fi # 規範日期 newdate="$(normdate "$@")" if [ $? -eq 1 ]; then exit 1 fi # 拆分規範後的日期格式,檢驗其合法有效性 month="$(echo $newdate | cut -d\ -f1)" day="$(echo $newdate | cut -d\ -f2)" year="$(echo $newdate | cut -d\ -f3)" msg1="$0: $3 is not a leap year, so Feb doesn't have 29 days." msg2="$0: bad day value: $month does't have $2 days." if ! exceedsDaysInMonth $month $2; then if [ "$month" = "Feb" -a $2 -eq 29 ]; then if ! isLeapYear $3; then echo $msg1 >&2 exit 1 fi else echo $msg2 >&2 exit 1 fi fi echo "valid date: $newdate" exit 0