Blog de Raúl Salinas

true/false as booleans in bash

Many people use this common pattern in bash:

BUILD=1

if [ "$BUILD" -ne 0 ]
then
    make
fi

I have been using a more compact approach for years:

BUILD=true

if $BUILD
then
    make
fi

If we do not want to pre-initialize the variables:

if ${BUILD:-false}   ## Or true, whatever the default is
then
    make
fi

Of course with this mechanism we are trusting the variable contents, which is usually the case in the immense majority of cases.

Beyond true/false: commands as booleans

The real power of this pattern is that the variable can hold any command, not just true or false. The variable is executed and its exit code determines the branch:

COLOR="tty -s"      # true if stdout is a terminal, false if redirected

if $COLOR; then
    echo -e "\033[1mBold text\033[0m"
else
    echo "Plain text"
fi

This lets you write code that adapts its behaviour at runtime without if chains:

VERBOSE=true        # always verbose
VERBOSE=false       # never verbose
VERBOSE="tty -s"    # verbose only on a terminal

$VERBOSE && echo "Debug: $value"

Security note: never use this pattern if the variable can be set from outside the script (user input, environment, config file). if $BUILD executes the variable contents as a command — so BUILD="rm -rf /" would be catastrophic. In those cases, compare explicitly: [[ "$BUILD" == "true" ]].