swag antiswag swag antiswag - 1 year ago 87
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}$" ]
echo "Please retype the start date (YYYY-MM-DD):"
read startDate

Answer Source

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:

while [[ ! $date =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]; do
    echo "enter date (YYYY-MM-DD)"
    read $date