Shell 腳本使用者輸入日期驗證

Shell 腳本使用者輸入日期驗證

我將如何在 shell 腳本中對使用者輸入執行日期驗證?如果使用者以錯誤的格式輸入日期,我想通知他們。正確的格式是 YYYYMMDD。

答案1

此方法將輸入視為字串,然後解析並測試它的格式是否正確。在此表單中,我還檢查日期中的欄位是否正確,但如果不需要,您可以刪除這些條件。

#!/bin/bash
echo -n "Enter the date as YYYYMMDD >"
read date
if [ ${#date} -eq 8 ]; then
    year=${date:0:4}
    month=${date:4:2}
    day=${date:6:2}
    month30="04 06 09 11"
    leapyear=$((year%4)) # if leapyear this is 0
    if [ "$year" -ge 1901 -a "$month" -le 12 -a "$day" -le 31 ]; then
            if [ "$month" -eq 02 -a "$day" -gt 29 ] || [ "$leapyear" -ne 0 -a "$month" -eq 02 -a "$day" -gt 28 ]; then
                    echo "Too many days for February... try again"; exit
            fi
            if [[ "$month30" =~ "$month" ]] && [ "$day" -eq 31 ]; then
                    echo "Month $month cannot have 31 days... try again"; exit
            fi
    else echo "Date is out of range"; exit
    fi
else echo "try again...expecting format as YYYYMMDD"; exit
fi
echo "SUCCESS!"
echo "year: $year  month: $month  day: $day"

答案2

您可能喜歡接受多種格式並將其轉換為標準形式的選項;該date命令可以幫助:

$ day=$(unset day;
        until date -d "${day:-XXX}" '+%Y%m%d' 2>/dev/null
          do read -p "Which day? " day
        done)
Which day? 
Which day? weds 
Which day? friday
$ echo $day
20150508

相關內容