0

I have the following snippet, where the function test echoes false. I use the echoed value in an if statement with shell substitution:

#!/usr/bin/env bash

test () {
    echo "false"
}

if [[ "$(test)" -eq "true" ]]
then
    echo hello world
fi

I would expect to above to not print hello world, because I assume this would end up saying [[ "false" -eq "true" ]].

However when I run the script it echoes hello world.

Jimmy Sanchez
  • 721
  • 2
  • 7
  • 17
  • 1
    `[[ false -eq true ]]` is true, because the strings `false` and `true` both have the same integer value -- of `0` -- unless someone defines a variable by that name with a different value (ie. `false=1`). – Charles Duffy May 07 '18 at 22:06

2 Answers2

0

If you read the manual for test, you would realize that the -eq, -gt, and -lt test conditions are only for numeric values.

INTEGER1 -eq INTEGER2
    INTEGER1 is equal to INTEGER2

i.e., if [ 0 -gt 1 ];

For string comparison in bash, simply use an =.

Try using

if [[ "$(test)" = "true" ]]

This will give you the expected behavior.

Matt Clark
  • 27,671
  • 19
  • 68
  • 123
0

try this

#!/usr/bin/env bash
test () {
    echo "false"
}

if [[ "$(test)" = "true" ]]
then
    echo hello world
fi
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
Eby Jacob
  • 1,418
  • 1
  • 10
  • 28