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

Why when entering bash: if [ false ]; then echo 'ok'; fi; if [ false ]; then echo 'ok'; fi; do i get the string ok as a result? I can get a similar result when using a variable: ok=false; if [ $ok ]; then echo 'ok'; fi; ok=false; if [ $ok ]; then echo 'ok'; fi;

+7
source share
2 answers

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

+10
source

true and false not built-in keywords for boolean in bash in the same way as for other programming languages

You can simulate checking the true / false state 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 do:

 if [ false ] 

It implicitly translates to

 if [ -n "false" ] 

Where -n means "test if the length of this length is greater than 0: logically true, if so, logically false otherwise"

Next to it, true and false really do something, but these are the commands:

 man true man false 

More about them.

+3
source

All Articles