Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bourne: if statement testing exit status

What is the difference:

if IsServerStarted ; then ...

and

if [ IsServerStarted -eq 0 ] ; then ...

Seems to me that these two statements should be equivalent? Strangely the second statement is always true.

like image 927
sixtyfootersdude Avatar asked Jan 22 '23 05:01

sixtyfootersdude


1 Answers

The following runs the shell function or executable in $PATH named IsServerStarted, and if its exit code is 0 (i.e. true), runs the then branch. If such a function or executable does not exist, the exit code will be non-0 (i.e. false) and the then branch will be skipped.

if IsServerStarted ; then ...

The following has [ (aka test) check whether IsServerStarted is an integer equal to 0, which (IsServerStarted not even containing a single digit) is always false. Thus, [ exits with a non-0 (i.e. false) code and the then branch is always skipped.

if [ IsServerStarted -eq 0 ] ; then ...
like image 102
ndim Avatar answered Jan 30 '23 08:01

ndim