Bash双方括号正则表达式匹配问题

标签 bash

考虑下面的代码:

$ 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 中所做的。

问题是为什么 56 行没有打印 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/

相关文章:

linux - 非破折号相关的错误替换错误

bash - 从 bash 控制台重启服务器

git - "bash: __gitdir: command not found"终端错误

bash - echo backspace 开关创建换行符

linux + 将 sh 脚本转换为 bash + bash 是否支持以前的 sh 脚本

linux - 根据创建时间删除文件

bash - 在 bash 脚本中并行运行数组中的每个元素

linux - 检测参数的数量和传递给 bash 的值

python - 忽略错误代码 141 的 Bash pipefail

bash - 在 bash 中内联插入文件描述符 3 的输出