Bash shell: How to check for specific date format?

末鹿安然 提交于 2019-12-04 19:27:07

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.

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-dd you can do both regex and date validation. regex only for the format, and date for the date validation.

because date -d accepts string like 02/27/2012 too.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!