Validate date format in a shell script Validate date format in a shell script unix unix

Validate date format in a shell script


Use date

date "+%d/%m/%Y" -d "09/99/2013" > /dev/null  2>&1 is_valid=$?

The date string must be in "MM/DD/YYYY" format.

If you do not get 0 then date is in invalid format.


The simplest solution, that still works perfectly, is the following :

if [[ $1 =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] && date -d "$1" >/dev/null 2>&1   ...

It consists in combining 2 checks :

  • the first part checks that $1 is of this format : NNNN-NN-NN
  • the second part checks that it is a valid date

You need the two checks because :

  • if you don't do the first check, date will exit with code 0 even if your variable is a valid date in another format
  • if you don't do the second check, then you can end up with a 0 even for variables such as 2016-13-45


This function expects 2 strings,a format string, a date string

The format string uses the codes from the date command but does not include the '+'

The function returns 0 if the provided date matches the given format, otherwise it returns 1

Code (my_script.sh)

#!/bin/bashdatecheck() {    local format="$1" d="$2"    [[ "$(date "+$format" -d "$d" 2>/dev/null)" == "$d" ]]}date_test="$1"echo $date_testif datecheck "%d %b %Y" "$date_test"; then    echo OKelse    echo KOfi

Output

$ ./my_script.sh "05 Apr 2020"05 Apr 2020OK$ ./my_script.sh "foo bar"foo barKO