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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With