Checking if a variable is a date with the correct format
I would like to check if the variable is a date (not a problem), but if the variable has the correct date format (yyyy-MM-dd).
I tried:
export DATE_REFRESH=01/01/1900
if ! date -d $DATE_REFRESH "+%Y-%m-%d"; then
echo "$DATE_REFRESH is not a valid date. Expected format is : yyyy-MM-dd"
fi
But that won't work.
I can try:
if [[ $DATE_REFRESH == [0-9][0-9][0-9][0-9]-[0-1][0-9]-[0-3][0-9] ]]
But I don't want to have a date before 33/19/2000 ...
+3
source to share
2 answers
You have to do both tests because a line date
can be everything, see the man page:
... -date = STRING is basically a free human readable format. a string such as ...
Use this:
if ! [[ "$DATE_REFRESH" =~ ^[[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}$ ]] \
|| ! date -d $DATE_REFRESH >/dev/null 2>&1; then
echo "$DATE_REFRESH is not a valid date. Expected format is : yyyy-MM-dd"
fi
+2
source to share