0

I would like to test if a condition is true or false. Here is a sample bash script:

#!/bin/bash
set -x
var=foo
if [[ $var==bar ]]
then
        echo $var is bar
else
        echo $var is not bar
fi
set +x

I expect that the output will be foo is not bar, but I get the following output instead: foo is bar

While viewing the debug output, I noticed that the condition was being evaluated with -n:

+ var=foo
+ [[ -n foo==bar ]]
+ echo foo is bar
foo is bar
+ set +x

On the Bash Conditional Expressions man page it says

-n string

True if the length of string is non-zero.

But I'm not interested in whether the string length is non-zero, but rather whether the two strings are equal to each other.

1

1 Answer 1

6

[[ is behaving as designed, because $var==bar is not actually a conditional expression comparing two strings, but a single string (that happens to contain two equal sign characters). Since [[ ... ]] only contains a string rather than a conditional expression, its default is to use the -n flag to check whether the string is not zero-length, and thus evaluates with an exit code of 0. This is not what you intended, though, so if you would like to evaluate whether $var is equal to bar, use spaces around the == operator to turn it into a conditional expression:

[[ $var == bar ]]

From the conditional expressions man page:

string1 == string2

string1 = string2

True if the strings are equal. When used with the [[ command, this performs pattern matching as described above (see Conditional Constructs).

‘=’ should be used with the test command for POSIX conformance.

4
  • @Kusalananda the problem occurs with [ ... ] also; do you think it is important to differentiate in this case? I get the same behavior with -n whether I use [ or [[
    – enharmonic
    Commented Oct 22, 2019 at 21:25
  • [ is the same as test and works the same. [[ is different. For example, variables do not need to be quoted within [[ ... ]], but they would need to be quoted with test or [ ... ] (as they are ordinary utilities, while [[ is a keyword). Also, -n will not occur in the xtrace output when using [ or test in the way done in the question.
    – Kusalananda
    Commented Oct 22, 2019 at 21:30
  • @Kusalananda no need for quotes ? so if bar is empty, [[ -n $bar ]] is a valid expression ? Commented Oct 24, 2019 at 6:27
  • @Pierre-AntoineGuillaume Yes. Also, [[ -z $bar ]] && echo ok would output ok for an empty or unset $bar.
    – Kusalananda
    Commented Oct 24, 2019 at 6:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .