bash [[ [a] == [a] ]] 不对?方括号影响比较结果
bash [[ [a] == [a] ]] not true? square bracket affect compare result
有人知道为什么会这样吗?这是 bash 的错误吗?
x='mnt:[4026532411]'
[[ $x == $x ]] && echo OK
我期待结果 OK
,但没有。
当然,这行得通
[[ "$x" == "$x" ]] && echo OK
但据我所知,bash [[ ]] 有一个优点就是比较时不需要引用 var。
x='a b'
[[ $x == $x ]] && echo OK
有效。
讽刺的是
x='mnt:[4026532411]'
[[ $x != $x ]] && echo Oh my god
结果是天啊
==
和 !=
的不带引号的右侧被视为模式,而不是文字字符串。 mnt:[4026532411]
将匹配 mnt:
后跟 0、1、2、3、4、5 或 6 中的 一个 ,因为模式 mnt:[4026532411]
和 mnt:[0123456]
是等价的。要匹配lieral字符串,你需要引用扩展。
x='mnt:[4026532411]'
[[ $x == "$x" ]] && echo OK
您看到的是执行 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 under Pattern Matching, as if the extglob
shell option were enabled.
您可能已经知道,shell 中的 [...]
允许从
字符组。也就是说,给定文件:
$ ls
fileA fileB fileC fileD
运行 ls file[AB]
将产生:
fileA fileB
所以在你的表达中,mnt:[1234]
被解释为类似
时尚。
有人知道为什么会这样吗?这是 bash 的错误吗?
x='mnt:[4026532411]'
[[ $x == $x ]] && echo OK
我期待结果 OK
,但没有。
当然,这行得通
[[ "$x" == "$x" ]] && echo OK
但据我所知,bash [[ ]] 有一个优点就是比较时不需要引用 var。
x='a b'
[[ $x == $x ]] && echo OK
有效。
讽刺的是
x='mnt:[4026532411]'
[[ $x != $x ]] && echo Oh my god
结果是天啊
==
和 !=
的不带引号的右侧被视为模式,而不是文字字符串。 mnt:[4026532411]
将匹配 mnt:
后跟 0、1、2、3、4、5 或 6 中的 一个 ,因为模式 mnt:[4026532411]
和 mnt:[0123456]
是等价的。要匹配lieral字符串,你需要引用扩展。
x='mnt:[4026532411]'
[[ $x == "$x" ]] && echo OK
您看到的是执行 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 under Pattern Matching, as if the extglob shell option were enabled.
您可能已经知道,shell 中的 [...]
允许从
字符组。也就是说,给定文件:
$ ls
fileA fileB fileC fileD
运行 ls file[AB]
将产生:
fileA fileB
所以在你的表达中,mnt:[1234]
被解释为类似
时尚。