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

相关内容