Daniel Marchand
Daniel Marchand

Reputation: 644

Easily Check Boolean of a Bash Statement

I'd like to check whether $MY_EXPRESSION is true or false in bash.

I know I can check this with something like

if [ $MY_EXPRESSION ]; then echo "true" else echo "false

But I wanted to know if there was a more compact way of checking, perhaps a utility function I haven't heard of. Something ideally like:

$bool $MY_EXPRESSION 

Upvotes: 1

Views: 97

Answers (1)

tripleee
tripleee

Reputation: 189487

Bash variables are strings, or arrays of strings; there is no separate concept of a boolean.

A common arrangement is to have the empty string mean "false". Then the syntax you are using is almost right, except you will want to quote the variable.

Tangentially, perhaps also explore the && and || shorthands.

[ "$MY_EXPRESSION" ] && echo "True" || echo "False"

The [ (aka test) command has a largish number of options to check for other conditions, such as string or numeric equality, whether a file with the indicated name exists, or a directory, or etc. This is portable to other shells; but if you only need your script to work in Bash, you might prefer the [[ command which is slightly easier to work with, and offers more features.

Upvotes: 2

Related Questions