Bash shell: How to check for specific date format?

一曲冷凌霜 提交于 2019-12-06 14:23:14

问题


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

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?


回答1:


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.



来源:https://stackoverflow.com/questions/16530912/bash-shell-how-to-check-for-specific-date-format

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