Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 769
swag antiswag Avatar asked Jan 06 '23 04:01

swag antiswag


2 Answers

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
like image 158
fedorqui 'SO stop harming' Avatar answered Jan 16 '23 01:01

fedorqui 'SO stop harming'


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"
like image 37
Wei Shen Avatar answered Jan 16 '23 01:01

Wei Shen