溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

shell腳本中怎么判斷輸入的日期是否正確

發布時間:2021-08-02 14:07:57 來源:億速云 閱讀:278 作者:Leah 欄目:開發技術

這篇文章將為大家詳細講解有關shell腳本中怎么判斷輸入的日期是否正確,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。


下面是代碼

#!/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 $1" >&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 % 400))" -eq 0 ] ; then
  return 0 # yes, it's a leap year
 elif [ "$((year % 100))" -eq 0 ] ; then
  return 1
 else
  return 0
 fi
}
## Begin main script

if [ $# -ne 3 ] ; then
 echo "Usage: $0 month day year" >&2
 echo "Typical input formats are 8 3 2002" >&2
 exit 1
fi

# Normalize 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 the appropriate value
 case $1 in
  01|1 ) monthd="Jan"  ;; 02|2 ) monthd="Feb"  ;;
  03|3 ) monthd="Mar"  ;; 04|4 ) monthd="Apr"  ;;
  05|5 ) monthd="May"  ;; 06|6 ) monthd="Jun"  ;;
  07|7 ) monthd="Jul"  ;; 08|8 ) monthd="Aug"  ;;
  09|9 ) monthd="Sep"  ;;   10) monthd="Oct"  ;;
    11) monthd="Nov"  ;;   12) monthd="Dec"  ;;
  * ) echo "$0: Unknown numeric month value $1" >&2; exit 1
  esac
  return 0
}

monthnoToName $1

month="$monthd"
 day="$2"
 year="$3"
 
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

分析:
1)首先判斷用戶輸入的參數個數是否正確,接著case $1 in 語句判斷月份是否合理。
2)monthnoToName 函數之前出現在我們之前的第03個腳本案例中,用來轉換輸入的數字日期為字符串。
3) exceedsDaysInMonth 用來判斷天數是否超過對應月的最大天數,緊跟著 if [ "$month" = "Feb" -a "$2" -eq "29" ] ; then if ! isLeapYear $3 ; then 用來判斷閏年2月的特殊情況
4)總體的感覺是腳本還是很緊湊的,特別是在判斷閏年與2月的關系的那段代碼,有點意思。

關于shell腳本中怎么判斷輸入的日期是否正確就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女