Adam Sznajder
Adam Sznajder

Reputation: 9206

Why if [ false ]; then echo 'ok'; fi; prints ok?

Why when I type in bash: if [ false ]; then echo 'ok'; fi; I get ok string as a result? The similiar result I can get also when using variable: ok=false; if [ $ok ]; then echo 'ok'; fi;

Upvotes: 7

Views: 1397

Answers (2)

twalberg
twalberg

Reputation: 62369

if [ false ] is equivalent to if [ -n "false" ] - it's testing the length of the string. If you are trying to test the exit code of /bin/false, use if false (no [, which for many, but not all, modern shells is a shell builtin roughly equivalent to /usr/bin/[ or /usr/bin/test).

Upvotes: 10

sampson-chen
sampson-chen

Reputation: 47269

true and false are not builtin keywords for boolean in bash the same way they are for other programming languages

You can simulate the test of true / false condition of a variable as follows:

cond1="true"
cond2="false"

if [ "$cond1" = "true" ]; then
    echo "First condition is true"
fi

if [ "$cond2" = "false" ]; then
    echo "Second condition is false"
fi

When you are doing:

if [ false ]

It implicitly translates to

if [ -n "false" ]

Where the -n denotes "test if this has length greater than 0: logically true if so, logically false otherwise"

Aside - true and false actually do do something, but they are commands:

man true
man false

To read more about them.

Upvotes: 3

Related Questions