One of the arguments that my script receives is a date in the following format: yyyymmdd
.
I want to check if I get a valid date as an input.
How can I do this? I am trying to use a regex like: [0-9]\{\8}
One of the arguments that my script receives is a date in the following format: yyyymmdd
.
I want to check if I get a valid date as an input.
How can I do this? I am trying to use a regex like: [0-9]\{\8}
In bash version 3 you can use the '=~' operator:
Reference: http://tldp.org/LDP/abs/html/bashver3.html#REGEXMATCHREF
Where the usage of a regex can be helpful to determine if the character sequence of a date is correct, it cannot be used easily to determine if the date is valid. The following examples will pass the regular expression, but are all invalid dates: 20180231, 20190229, 20190431
So if you want to validate if your date string (let's call it
datestr
) is in the correct format, it is best to parse it withdate
and askdate
to convert the string to the correct format. If both strings are identical, you have a valid format and valid date.You can say:
Or more accurate:
That is, you can define a regex in bash matching the format you want. This way you can do:
Note this is based on the solution by Aleks-Daniel Jakimenko in User input date format verification in bash.
In other shells you can use grep. If your shell is POSIX compliant, do
In fish, which is not POSIX-compliant, you can do
I would use
expr match
instead of=~
:This is better than the currently accepted answer of using
=~
because=~
will also match empty strings, which IMHO it shouldn't. Supposebadvar
is not defined, then[[ "1234" =~ "$badvar" ]]; echo $?
gives (incorrectly)0
, whileexpr match "1234" "$badvar" >/dev/null ; echo $?
gives correct result1
.We have to use
>/dev/null
to hideexpr match
's output value, which is the number of characters matched or 0 if no match found. Note its output value is different from its exit status. The exit status is 0 if there's a match found, or 1 otherwise.Generally, the syntax for
expr
is:Or:
where
$lead
is a regular expression. Itsexit status
will be true (0) iflead
matches the leading slice ofstring
(Is there a name for this?). For exampleexpr match "abcdefghi" "abc"
exitstrue
, butexpr match "abcdefghi" "bcd"
exitsfalse
. (Credit to @Carlo Wood for pointing out this.A good way to test if a string is a correct date is to use the command date: