swag antiswag swag antiswag - 7 months ago 23
Bash Question

Shell REGEX for date

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

Answer

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
Comments