Star Hype News.

Premium celebrity moments with standout appeal.

news

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 0

If I execute 0 in the bash, it says:

0: command not found

So 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?

2

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy