Bash shell中:如何检查特定日期格式? [英] Bash shell: How to check for specific date format?
问题描述
我要看看哪些检查Bash的shell脚本,如果一个shell变量中包含一个数字:
I have a Bash shell script which checks to see if a shell variable contains a number:
if ! [[ "$step" =~ ^[0-9]+$ ]]
then
exec >&2; echo "error: $step is Not a step number.";
exit 1
fi
现在我需要做类似的检查,看是否有变量包含所需的格式是 YYYY-MM-DD
(例如日期:今天是2013年5月13日)与破折号。这怎么能与Bash shell中一个普通的前pression做还是我需要一个外部程序来做到这一点?
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?
推荐答案
正则表达式是不要做这份工作的合适工具。
regex is not the right tool to do the job.
例如。
2013-02-29 (invalid date)
2012-02-29 (valid date)
2013-10-31 (valid date)
2013-09-31 (invalid date)
...
我会建议传递字符串日期-d
,然后检查返回值。如果返回0,一切都很好。如果返回1,无效的日期。
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.
例如:
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
如果您想强制格式为: YYYY-MM-DD
你可以做的两个正则表达式和日期
验证即可。正则表达式只为格式,和日期的时间验证。
if you want to force the format is yyyy-mm-dd
you can do both regex and date
validation. regex only for the format, and date for the date validation.
由于日期-d
接受字符串如 2012年2月27日
了。
这篇关于Bash shell中:如何检查特定日期格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!