bash bash中的用户输入日期格式验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18748933/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
user input date format verification in bash
提问by lukabix22
So I'm trying to write a simple script in bash that asks user for input date in following format (YYYY-dd-mm). Unfortunately I got stuck on first step, which is verifying that input is in correct format. I tried using 'date' with no luck (as it returns actual current date). I'm trying to make this as simple as possible. Thank you for your help!
所以我试图在 bash 中编写一个简单的脚本,要求用户以以下格式(YYYY-dd-mm)输入日期。不幸的是,我被困在第一步,即验证输入的格式是否正确。我尝试使用“日期”但没有运气(因为它返回实际的当前日期)。我正在努力使这尽可能简单。感谢您的帮助!
回答by Aleks-Daniel Jakimenko-A.
Using regex:
使用正则表达式:
if [[ $date =~ ^[0-9]{4}-[0-3][0-9]-[0-1][0-9]$ ]]; then
or with bash globs:
或使用 bash glob:
if [[ $date == [0-9][0-9][0-9][0-9]-[0-3][0-9]-[0-1][0-9] ]]; then
Please note that this regex will accept a date like 9999-00-19
which is not a correct date. So after you check its possible correctness with this regex you should verify that the numbers are correct.
请注意,此正则表达式将接受类似9999-00-19
不正确日期的日期。因此,在使用此正则表达式检查其可能的正确性后,您应该验证数字是否正确。
IFS='-' read -r year day month <<< "$date"
This will put the numbers into $year
$day
and $month
variables.
这会将数字放入$year
$day
和$month
变量中。
回答by runlevel0
date -d "$date" +%Y-%m-%d
The latter is the format, the -d allows an input date. If it's wrong it will return an error that can be piped to the bit bucket, if it's correct it will return the date.
后者是格式,-d 允许输入日期。如果它是错误的,它将返回一个可以通过管道传输到位桶的错误,如果它是正确的,它将返回日期。
The format modifiers can be found in the manpage of date man 1 date
. Here an example with an array of 3 dates:
格式修饰符可以在 date 的联机帮助页中找到man 1 date
。这是一个包含 3 个日期的数组的示例:
dates=(2012-01-34 2014-01-01 2015-12-24)
for Date in ${dates[@]} ; do
if [ -z "$(date -d $Date 2>/dev/null)" ; then
echo "Date $Date is invalid"
else
echo "Date $Date is valid"
fi
done
Just a note of caution: typing man date
into Google while at work can produce some NSFW results ;)
请注意:man date
在工作时输入Google 会产生一些 NSFW 结果;)