Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 245
osexp2003 Avatar asked Jun 23 '18 15:06

osexp2003


People also ask

What is difference between using and == In a Bash double square bracket?

Double Brackets i.e. [[]] is an enhanced (or extension) version of standard POSIX version, this is supported by bash and other shells(zsh,ksh). In bash, for numeric comparison we use eq , ne , lt and gt , with double brackets for comparison we can use == , !=

What does square bracket do Bash?

The square brackets are a synonym for the test command. An if statement checks the exit status of a command in order to decide which branch to take. grep -q "$text" is a command, but "$name" = 'Bob' is not--it's just an expression.

What does double brackets mean in Bash?

Double brackets in bash are not a command but a part of the language syntax. This means they can react more tolerantly to 'disappearing' arguments: $ [[ $a = $b ]] || echo "unequal" unequal.

What does double brackets mean in Linux?

The double bracket is a “compound command” where as test and the single bracket are shell built-ins (and in actuality are the same command). Thus, the single bracket and double bracket execute different code. The test and single bracket are the most portable as they exist as separate and external commands.


1 Answers

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
like image 60
chepner Avatar answered Sep 30 '22 02:09

chepner