bash [[ [a] == [a] ]] not true? square bracket affect compare result

丶灬走出姿态 提交于 2019-12-03 16:25:09

问题


Anyone know why this happens? Is this a bug of bash?

x='mnt:[4026532411]'

[[ $x == $x ]] && echo OK

I am expecting result OK, but it did not.

Of course, this works

[[ "$x" == "$x" ]] && echo OK

But as I know, bash [[ ]] have a merit that no need to quote var when compare.

x='a b'
[[ $x == $x ]] && echo OK

works.

Ironical things is

x='mnt:[4026532411]'

[[ $x != $x ]] && echo Oh my god

result is Oh my god


回答1:


The unquoted right-hand side of == and != is treated as a pattern, not a literal string. mnt:[4026532411] will match mnt: followed by exactly one of 0, 1, 2, 3, 4, 5, or 6, since the patterns mnt:[4026532411] and mnt:[0123456] are equivalent. To match the lieral string, you need to quote the expansion.

x='mnt:[4026532411]'

[[ $x == "$x" ]] && echo OK



回答2:


What you are seeing is do do this sentence from the bash man page:

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.

As you may already know, [...] in the shell allows matching from a group of characters. That is, given the files:

$ ls
fileA fileB fileC fileD

Running ls file[AB] will yield:

fileA fileB

So in your expression, mnt:[1234] is interpreted in a similar fashion.



来源:https://stackoverflow.com/questions/51002801/bash-a-a-not-true-square-bracket-affect-compare-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!