Bash boolean expression and its value assignment

Rather than using ... && BOOL=0 || BOOL=1 suggested in the currently-accepted answer, it's clearer to use true and false.

And since this question is about bash specifically (not POSIX shell), it's also better to use [[ instead of [ (see e.g. 1 and 2), which allows using == instead of =.

So if you had to use a one-liner for something like this in bash, the following would be better:

[[ "$PROCEED" == "y" ]] && should_proceed=true || should_proceed=false

Then you can use the derived variable ergonomically in boolean contexts...

if $should_proceed; then
  echo "Proceeding..."
fi

...including with the ! operator:

if ! $should_proceed; then
  echo "Bye for now."
  exit 0
fi

I would suggest:

[ "$PROCEED" = "y" ] || BOOL=1

This has the advantage over checking $? that it works even when set -e is on. (See writing robust shell scripts.)


You could do:

[ "$PROCEED" = "y" ] ; BOOL=$?

If you're working with set -e, you can use instead:

[ "$PROCEED" = "y" ] && BOOL=0 || BOOL=1

BOOL set to zero when there is a match, to act like typical Unix return codes. Looks a bit weird.

This will not throw errors, and you're sure $BOOL will be either 0 or 1 afterwards, whatever it contained before.

Tags:

Bash