-1

Am trying to validate that the first (and only) parameter a user passes into a script is a valid date in the format dd/mm/yyyy e.g. 13/01/2022.

I started off with a regex which was fine but doesn't validate the date. I found the suggestion (on stack overflow) to use date -d "$1" '<date format>' and then use that to move forwards or error.

I can get this to validate a YYYY-MM-DD date but DD-MM-YYYY or my preferred DD/MM/YYYY always throw an invalid date.

I have hardcoded this to today's date in the code example below and have been changing to date format string.

I can get date '+%d/%m/%Y' on the command line to return today's date in the format I want. Is there a limitation on the format I can validate?

This throws Invalid date for 02/12/2022 (today's date of posting).

#datestr=$1
datestr=$(date '+%d/%m/%Y')
echo $datestr
if [[ "$datestr" == $(date -d "$datestr" '+%d/%m/%Y') ]]; then
     echo "Valid date"
else
     echo "Invalid date"
fi

TIA

[Edit - my starting point for the solution] Check if a string matches a regex in Bash script

Sevs
  • 9
  • 3

1 Answers1

0

Using GNU date and bash:

#!/bin/bash

datestr=$1
if [[ $datestr = [0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9] ]] &&
   date -d "${datestr:6}-${datestr:3:2}-${datestr:0:2}" &>/dev/null
then
    echo "Valid date"
else
    echo "Invalid date"
fi
M. Nejat Aydin
  • 9,597
  • 1
  • 7
  • 17