USING-logical-AND-operator-FOR-concise-conditionals

Using && operator for concise conditionals

TRUE=0
FALSE=1

[[ <CONDITION> ]] && {
   # Do stuff
}

✅ SAFE WITHOUT ||

This pattern works as a simple if-statement replacement:

[[ "${_GT_EAI__SHOULD_PRINT_PWD_AFTER_RUN:?}" == "${TRUE}" ]] && {
  echo.dim "PWD: $PWD" >&2
}

❌ NOT SAFE WITH ||

The || executes when EITHER:

  • The condition is false, OR
  • Any command inside the block returns non-zero
[[ <CONDITION> == "${TRUE}" ]] && {
   # do-stuff
} || # This runs if: condition is false OR do-stuff failed!

Example demonstrating the problem:

TRUE=0
FALSE=1

command2() {
  echo "command 2-fails"
  return 1
}

main() {
  FLAG="${TRUE}"  # Flag is set to TRUE (0)

  # RISKY - the || applies to the whole && chain
  [[ "${FLAG}" == "${TRUE}" ]] && {
      echo "Flag is true, running commands..."
      command2  # This fails with exit code 1
  } || echo "Flag was false"  # WRONG! Runs even though FLAG was TRUE!
}

main "${@}" || exit 1

Output:

Flag is true, running commands...
command 2-fails
Flag was false

Safe alternative with ||:

# Use a proper if-statement when you need an else clause
if [[ "${FLAG}" == "${TRUE}" ]]; then
    echo "Flag is true"
    command2  # Failure here won't trigger else
else
    echo "Flag was false"
fi

Using == is cleaner here - it makes it clear we're comparing string values, not doing arithmetic comparison.