考虑下面的代码:
$ 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
以上是我在 bash shell 中所做的。
问题是为什么 5
和 6
行没有打印 found
?
我想我已经知道答案了,但我正在寻找一个简单易懂的答案。
综上所述,当=~
右边使用变量(双引号内)时,双引号是否只是用于变量扩展?
最佳答案
假设您正在运行 Bash 3.2 或更新版本,bash manual (向下滚动到 [[…]]
的描述)状态:
Any part of the pattern may be quoted to force the quoted portion to be matched as a string.
还有:
If the pattern is stored in a shell variable, quoting the variable expansion forces the entire pattern to be matched as a string.
在 Bash 3.2 之前,您提供的示例会按预期工作。
关于Bash双方括号正则表达式匹配问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37815311/