6

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
swag antiswag
  • 349
  • 1
  • 4
  • 12

2 Answers2

11

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
Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
1

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"
Wei Shen
  • 2,014
  • 19
  • 17