1

This block of code keeps echoing "they are equal" Why?

#!/bin/bash

foo="hello"
bar="h"
if [[ "$foo"=="$bar" ]]; then
        echo "they are equal"
else
        echo "they are not equal"
fi

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • 1
    the operators will always need spaces around them, but also note fwiw that the `[[...]]` works differently than the `[...]` ; one difference is that you actually don't need the quotes (`"..."`) with the double `[[...]]` see https://tldp.org/LDP/abs/html/comparison-ops.html and https://tldp.org/LDP/abs/html/testconstructs.html#DBLBRACKETS – michael Jun 09 '22 at 02:24
  • 1
    @michael That's not entirely true; if the string on the right side of a `[[ == ]]` test isn't quoted, it's treated as a glob (wildcard) pattern, which can cause [weird](https://stackoverflow.com/questions/51002801) [problems](https://stackoverflow.com/questions/53656293). IMO it's much easier and safer to just always double-quote variable references (unless there's a specific reason not to, like if you *want* it treated as a glob pattern) than it is to try to remember all the weird exception cases like this. – Gordon Davisson Jun 09 '22 at 02:28
  • @GordonDavisson very true, I always quote as well, better safe than sorry. Main point being that `[[...]]` is different than `[...]`, and I should have just mentioned eg the differing operators available, but also quoting has "different" rules. – michael Jun 09 '22 at 19:48
  • 1
    ps: for those following along, here's the exact issue when NOT using quotes: `bar="hello"; foo="h*"; [[ $bar == $foo ]] && echo equal || echo nope` prints "equal", for better or worse, but `[[ "$bar" == "$foo" ]] && echo equal || echo nope` prints `nope` – michael Jun 09 '22 at 19:50

1 Answers1

3

The condition works based on the number of elements within it, and this particular issue is covered by this (paraphrased) part of the man-page:

string: True if the length of string is non-zero.

string1 == string2: True if the strings are equal.

In other words, a comparison needs three elements, meaning you need a space on either side of the ==.

Without that it's simply the one-element variant of the condition, which is true when the string is non-empty, as hello==h most definitely is.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953