Thomas Vincent
Thomas Vincent

Reputation: 198

ternary construction not equivalent with if then else

The following if/then test (in bash):

if [ 1 ]; then ls /undef_dummy > /dev/null 2>&1; else echo "else stmt"; fi

seems not equivalent to its ternary version:

(test 1) && ls /undef_dummy > /dev/null 2>&1 || echo "else stmt"

The first one will print nothing but the second one will print "else stmt".

This is because the || operator in the ternary version relates to the return status of either the test or the command executed if the test passes. But usually, we want the else statement to only relate to the test, so it's not safe to use the ternary version here.

Am I right?

Upvotes: 1

Views: 188

Answers (2)

devnull
devnull

Reputation: 123608

What you refer to as the ternary version is actually equivalent to:

if (test 1); then
  if ! ls /undef_dummy > /dev/null 2>&1; then
    echo "else stmt"
  fi
fi

and is pretty different from saying:

if [ 1 ]; then ls /undef_dummy > /dev/null 2>&1; else echo "else stmt"; fi

Upvotes: 1

anubhava
anubhava

Reputation: 785481

This command:

(test 1) && ls /undef_dummy > /dev/null 2>&1 || echo "else stmt"

|| is being evaluated because ls is returning non-zero return code to shell

If you use this command:

test 1 && date || echo "else stmt"

Then it will print date value instead of else stmt

With proper grouping your command:

test 1 && { ls /undef_dummy > /dev/null 2>&1 || true; } || echo "else stmt"

will not print anything

Upvotes: 4

Related Questions