Bash shell: How to check for specific date format?

2019-04-16 01:28发布

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?

标签: regex bash sh
1条回答
smile是对你的礼貌
2楼-- · 2019-04-16 02:06

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.

查看更多
登录 后发表回答