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 is not the right tool to do the job.
e.g.
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:
if you want to force the format is
yyyy-mm-dd
you can do both regex anddate
validation. regex only for the format, and date for the date validation.because
date -d
accepts string like02/27/2012
too.