Bash [[ 模式匹配不起作用

Bash [[ 模式匹配不起作用

有关条件构造的 Bash 参考部分说:

When the ‘==’ and ‘!=’ operators are used, the string to the right of the 
operator is considered a pattern and matched according to the rules described 
below in Pattern Matching, as if the extglob shell option were enabled. ...
An additional binary operator, ‘=~’, is available, with the same precedence as 
‘==’ and ‘!=’. When it is used, the string to the right of the operator is 
considered an extended regular expression and matched accordingly (as in regex 
3)). 

但后来我尝试这样做:

$ [[ -good == -* ]] ; echo $?
0
$ [[ -g == -* ]] ; echo $?
bash: syntax error in conditional expression
bash: syntax error near `-*'
$ [[ -g == -? ]] ; echo $?
bash: syntax error in conditional expression
bash: syntax error near `-?'

然后我尝试正则表达式匹配运算符=~

$ [[ -good =~ -.* ]] ; echo $?
0
$ [[ -g =~ -.* ]] ; echo $?
bash: syntax error in conditional expression
bash: syntax error near `-.*'
$ [[ -g =~ -.? ]] ; echo $?
bash: syntax error in conditional expression
bash: syntax error near `-.?'

为什么会出现语法错误?

答案1

==好吧,你必须小心或左边的文本=~不是!=其中之一Bash 条件表达式中识别的运算符

在您的情况下,-g测试位setgid集。如果您提供了在此上下文中不被识别为运算符的内容,那么它会起作用:

$ [[ -i == -* ]] ; echo $?
0
$ [[ -i == -? ]] ; echo $?
0
$ [[ -i =~ -.* ]] ; echo $?
0
$ [[ -i =~ -.? ]] ; echo $?
0

可靠地提供任何字符串的一种方法是引用它,因此它不会被识别为运算符,而只是被识别为字符串:

$ [[ "-good" == -* ]] ; echo $?
0
$ [[ "-g" == -* ]] ; echo $?
0
$ [[ "-g" == -? ]] ; echo $?
0
$ [[ "-good" =~ -.* ]] ; echo $?
0
$ [[ "-g" =~ -.* ]] ; echo $?
0
$ [[ "-g" =~ -.? ]] ; echo $?
0

但请注意不要引用右侧运算符,因为它会阻止将其识别为模式:

$ [[ "-good" == "-*" ]] ; echo $?
1
$ [[ "-g" == "-*" ]] ; echo $?
1
$ [[ "-g" == "-?" ]] ; echo $?
1
$ [[ "-good" =~ "-.*" ]] ; echo $?
1
$ [[ "-g" =~ "-.*" ]] ; echo $?
1
$ [[ "-g" =~ "-.?" ]] ; echo $?
1

答案2

我们应该将字符串放在引号内以将它们评估为字符串。如果我们尝试评估嵌入连字符(-)的字符串,那么 shell 会将其视为测试选项,而不是字符串。有关运营商的更多信息,您可以查看此这里

相关内容