How to validate date format in shell script

There are multiple ways you can validate date format in shell script. You can compare date format with regular expression or you can use inbuilt date command to check given date format is valid or not.

I am sharing a simple date command to validate the date in YYYY-mm-dd format.

#!/usr/bin/bash
d="2019-12-01"
date "+%Y-%m-%d" -d "$d" > /dev/null  2>&1
if [ $? != 0 ]
then
    echo Date $d NOT a valid YYYY-MM-DD date
    exit 1
fi

If you are validating the date in multiple places then you can replace the same code in a shell function

isValidDate() {
    local d="$1"
    date "+%Y-%m-%d" -d "$d" > /dev/null  2>&1
    if [ $? != 0 ]
    then
        echo "Date $d NOT a valid YYYY-MM-DD date"
        exit 1
    fi
}
#Uses
isValidDate "2019-12-01"

Please refer my earlier article to pass date as a mandatory argument in shell script.

Pass date as mandatory arguments in bash script

(Visited 5,608 times, 235 visits today)