Bash shell:如何检查特定的日期格式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16530912/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:25:39  来源:igfitidea点击:

Bash shell: How to check for specific date format?

regexbashsh

提问by Edward

I have a Bash shell script which checks to see if a shell variable contains a number:

我有一个 Bash shell 脚本,它检查一个 shell 变量是否包含一个数字:

   if ! [[ "$step" =~ ^[0-9]+$ ]]
   then
     exec >&2; echo "error: $step is Not a step number.";
     exit 1
   fi

Now I need to do a similar check to see if a variable contains the date in the required format which is YYYY-MM-DD(example: today is 2013-05-13)with the dashes. How can this be done with a regular expression in Bash shell or do I need an external program to do this?

现在我需要做一个类似的检查,看看一个变量是否包含带有破折号的所需格式的日期YYYY-MM-DD(例如:今天是 2013-05-13)。如何使用 Bash shell 中的正则表达式完成此操作,或者我是否需要外部程序来执行此操作?

回答by Kent

regex is not the right tool to do the job.

正则表达式不是完成这项工作的正确工具。

e.g.

例如

2013-02-29 (invalid date)
2012-02-29 (valid date)
2013-10-31 (valid date)
2013-09-31 (invalid date)
...

I would suggest passing the string to date -d, then check the return value. if return 0, everything is fine. if return 1, invalid date.

我建议将字符串传递给date -d,然后检查返回值。如果返回 0,则一切正常。如果返回 1,则日期无效。

for example:

例如:

kent$  date -d "2012-02-29" > /dev/null 2>&1
kent$  echo $?
0

kent$  date -d "2013-02-29" > /dev/null 2>&1
kent$  echo $?
1

if you want to force the format is yyyy-mm-ddyou can do both regex and datevalidation. regex only for the format, and date for the date validation.

如果你想强制格式是yyyy-mm-dd你可以做正则表达式和date验证。regex 仅用于格式,日期用于日期验证。

because date -daccepts string like 02/27/2012too.

因为也date -d接受字符串02/27/2012