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!!

Community
  • 1
  • 1
NoobEditor
  • 15,563
  • 19
  • 81
  • 112
  • Your problem is using `==` and `=~` within `[ ... ]`. You need to use double square brackets. Refer to the linked question. – devnull Feb 17 '14 at 06:23
  • @devnull : yeah, referred it the moment u posted....thankx mate!! :) – NoobEditor Feb 17 '14 at 06: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?? – NoobEditor Feb 17 '14 at 06:25
  • Moreover, avoid regex for validating date/time. You might want to refer to [this](http://stackoverflow.com/a/20326011/2235132) answer for an alternate approach. – devnull Feb 17 '14 at 06: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. – devnull Feb 17 '14 at 06:27
  • @devnull : i already visited your above url but problem is that i may have a custom time format, so m not at liberty to use standard methods...thats why i see `regex` as my only option!!! – NoobEditor Feb 17 '14 at 06:29

1 Answers1

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

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • +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??? – NoobEditor Feb 17 '14 at 06:17
  • 2
    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. – anubhava Feb 17 '14 at 06:32
  • didn't this thing...thanks!! :) – NoobEditor Feb 17 '14 at 06:38
  • @MortezaLSC: Yes sure you can do: `if [[ "$user_start_time" =~ $timePattern ]]; then echo "in if"; else echo "in else"; fi` – anubhava Feb 17 '14 at 06:54
  • 1
    I removed my comment... I found it yes thank you :) – MLSC Feb 17 '14 at 06:57