Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash double square brackets regex match issue

Tags:

bash

Consider the code below :

$ var1=bingo
$ var2=.ingo
$ if [[ "$var1" =~ $var2 ]]; then echo found; fi
found
$ if [[ $var1 =~ "$var2" ]]; then echo found; fi    # line 5
$ if [[ "$var1" =~ "$var2" ]]; then echo found; fi  # line 6
$ if [[ $var1 =~ $var2 ]]; then echo found; fi
found

Above is what I have done in bash shell.

Question is why didn't lines 5 and 6 print found?

I think I already know the answer, but I am looking for a simple easy to digest answer.

To conclude, when a variable(inside double quotes) is used at the right side of =~ , will the double quotes just serve for variable expansion?

like image 782
sjsam Avatar asked Jun 14 '16 14:06

sjsam


2 Answers

Assuming you are running Bash 3.2 or newer, the bash manual (scroll down to the description of [[…]]) states:

Any part of the pattern may be quoted to force the quoted portion to be matched as a string.

And further:

If the pattern is stored in a shell variable, quoting the variable expansion forces the entire pattern to be matched as a string.

Before Bash 3.2, the example you provided would have worked as you expected.

like image 127
Sean Bright Avatar answered Oct 13 '22 01:10

Sean Bright


When you use double quotes, the expanded pattern is treated literally. So the . actually being treated literally, not as a Regex token i.e. any single character.

Example:

$ if [[ $var1 =~ "$var2" ]]; then echo found; fi
+ [[ bingo =~ \.ingo ]]

$ if [[ $var1 =~ $var2 ]]; then echo found; fi
+ [[ bingo =~ .ingo ]]
+ echo found
found
like image 23
heemayl Avatar answered Oct 13 '22 00:10

heemayl