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

4
  • 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 tldp.org/LDP/abs/html/comparison-ops.html and tldp.org/LDP/abs/html/testconstructs.html#DBLBRACKETS Commented Jun 9, 2022 at 2: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 problems. 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. Commented Jun 9, 2022 at 2: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. Commented Jun 9, 2022 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 Commented Jun 9, 2022 at 19:50

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.