I am trying to fix the users input if they input an incorrect date format that is not (YYYY-MM-DD) but I cant figure it out. Here is what I have:
while [ "$startDate" != "^[0-9]{4}-[0-9]{2}-[0-9]{2}$" ]
do
echo "Please retype the start date (YYYY-MM-DD):"
read startDate
done
Instead of !=
, you have to use ! $var =~ regex
to perform regex comparisons:
[[ $date =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]
^^
So that your script can be like this:
date=""
while [[ ! $date =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]; do
echo "enter date (YYYY-MM-DD)"
read $date
done
Why not convert the incorrect format to desired one using date program:
$ date -d "06/38/1992" +"%Y-%m-%d"
1992-06-28
You can also check for conversion failure by checking return value.
$ date -d "06/38/1992" +"%Y-%m-%d"
date: invalid date ‘06/38/1992’
$ [ -z $? ] || echo "Error, failed to parse date"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With