Why does "if [ 0 ]" execute the "then" statement in bash script?
By Sarah Richards
This guide says:
An if/then construct tests whether the exit status of a list of commands is 0If I execute 0 in the bash, it says:
0: command not foundSo its exit status is not 0, and [ 0 ] should return a non-zero value exit status too. But it returns 0 exit status actually, and if [ 0 ] executes the then statement, not the else statement.
Can anyone explain it?
1 Answer
[ isn't part of the if statement, it is a command that evaluates expressions. The [ 0 ] returns true because the form [ Expression ] always evaluates to 0. If you try if [ 1 -eq 2 ] the then statement will not run.
Check the manual page for more info.
1