I have used the method posted for the following question, but I still have some issues.
Validate date format in a shell script
$ ./check_date.sh 20190109
Input date format 20190109 # this should report error!
$ ./check_date.sh 2019-0109
[ERROR]: Invalid input date format 2019-0109
$ ./check_date.sh 2019-01-09
Input date format 2019-01-09
$ cat ./check_date.sh
#!/usr/bin/bash
date '+%Y-%m-%d' -d $1 > /dev/null 2>&1
if [ "$?" -ne 0 ]; then
echo "[ERROR]: Invalid input date format $1"
exit 1
else
echo "Input date format $1"
fi
As you can see, I expect the input 20190109 will cause the script to report ERROR but instead it works without errors.
In summary, I need to validate the input date string so that it strictly follows the format YYYY-MM-DD.
Question> What should I do to get the script work as expected?
Thank you
echo "[ERROR]: Invalid input date format $1" >&220190109is accepted by the date command as input to the the-d, --date=STRINGswitch so you won't be able to use this approach to validate your format requirement.date +%Y-%m-%d -d "$1"