2

Assume a user fed time :

read -p "Enter the start time you want to start(hh:mm:ss) " user_start_time

and the regex :

timePattern="[0-2][0-3]:[0-5][0-9]:[0-5][0-9]"

if i do :

if [ "$user_start_time" == "$timePattern" ] 
#or if [ "$user_start_time" =~ "$timePattern" ]
then
         echo "in if"
else
         echo "in else"
fi

It doesn't validates.....being newbie, i understand comparison of int or string but how we go about time (date is there too, but date -d solves lot of problems)

There is this question too but couldn't understand the accepted answer!!

6
  • Your problem is using == and =~ within [ ... ]. You need to use double square brackets. Refer to the linked question. Commented Feb 17, 2014 at 6:23
  • @devnull : yeah, referred it the moment u posted....thankx mate!! :) Commented Feb 17, 2014 at 6:24
  • @devnull : a quick question, will it be a good practice if i always use [[ in validations rather than [ just to be on safer side?? Commented Feb 17, 2014 at 6:25
  • Moreover, avoid regex for validating date/time. You might want to refer to this answer for an alternate approach. Commented Feb 17, 2014 at 6:26
  • 1
    You can, it's just that [[ isn't as portable! If you're sure where your script would be running, I see no harm. Commented Feb 17, 2014 at 6:27

1 Answer 1

2

For regex matching you need to use =~ operator instead of == in BASH. So use it like this:

[[ "$user_start_time" =~ $timePattern ]] && echo "in if" || echo "in else"

Also you need to remove quotes around regex variable $timePattern

Sign up to request clarification or add additional context in comments.

5 Comments

+1 : so my code has 2 mistakes....Pattern should not be in quotes and double square brackets ....mmm.....when should the double square brackets and single square brackets be used?? i mean is there any criteria for it???
As a thumb rule always used [[ and ]] while using BASH. As you have noticed [ and ] don't even support =~ operator. [ was actually a command which is still supported for backward compatibility purpose but for all practical purposes in BASH use [[ and ]] as it is much more feature rich and efficient.
didn't this thing...thanks!! :)
@MortezaLSC: Yes sure you can do: if [[ "$user_start_time" =~ $timePattern ]]; then echo "in if"; else echo "in else"; fi
I removed my comment... I found it yes thank you :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.