Bourne:if语句测试退出状态

six*_*ude 4 shell if-statement sh exitstatus

有什么不同:

if IsServerStarted ; then ...
Run Code Online (Sandbox Code Playgroud)

if [ IsServerStarted -eq 0 ] ; then ...
Run Code Online (Sandbox Code Playgroud)

在我看来这两个陈述应该是等价的?奇怪的是,第二种说法总是如此.

ndi*_*dim 9

下面运行shell函数或可执行文件的$PATH命名IsServerStarted,而如果退出代码0(即真),运行的then分支.如果不存在这样的函数或可执行文件,则退出代码将为非0(即假)并且then将跳过分支.

if IsServerStarted ; then ...
Run Code Online (Sandbox Code Playgroud)

以下[(又称test)检查是否IsServerStarted是等于的整数0,其中(IsServerStarted甚至不包含单个数字)始终为false.因此,总是跳过[具有非0(即错误)代码和then分支的退出.

if [ IsServerStarted -eq 0 ] ; then ...
Run Code Online (Sandbox Code Playgroud)