Bourne:if 语句测试退出状态
有什么区别:
if IsServerStarted ; then ...
和
if [ IsServerStarted -eq 0 ] ; then ...
在我看来,这两个语句应该是等价的?奇怪的是,第二个陈述总是正确的。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以下代码运行
$PATH
中名为IsServerStarted
的 shell 函数或可执行文件,如果其退出代码为0
(即 true),则运行 <代码>然后分支。如果这样的函数或可执行文件不存在,则退出代码将为非0
(即假),并且then
分支将被跳过。下面的代码有
[
(又名test
)检查IsServerStarted
是否是一个等于0
的整数,其中(>IsServerStarted
甚至不包含一个数字)始终是false。因此,[
以非0
(即 false)代码退出,并且then
分支始终被跳过。The following runs the shell function or executable in
$PATH
namedIsServerStarted
, and if its exit code is0
(i.e. true), runs thethen
branch. If such a function or executable does not exist, the exit code will be non-0
(i.e. false) and thethen
branch will be skipped.The following has
[
(akatest
) check whetherIsServerStarted
is an integer equal to0
, which (IsServerStarted
not even containing a single digit) is always false. Thus,[
exits with a non-0
(i.e. false) code and thethen
branch is always skipped.实际上,第二个会给出一个错误,抱怨“IsServerStarted”不是一个有效的整数。它被认为是一个字符串常量,因此类似的事情
会成功(如果不相等则失败)。
关于您给出的第一个示例中的可执行文件或函数,ndim 是正确的。
需要考虑的还有几个变体:
在该变体中,
if
是根据变量IsServerStarted
中包含的命令(可执行文件或函数)的返回值进行评估的。因此,您可以设置IsServerStarted=true
,然后if
就会成功,因为true
是一个始终返回 true 的 shell 内置函数。您可以设置 IsServerStarted='grep popsicle freeze' ,并且 if` 会根据您是否没有零食而通过或失败。这只是测试变量是否等于零。如果它不是有效的整数,则会导致错误消息。
Actually, the second one will give an error complaining that "IsServerStarted" is not a valid integer. It's considered a string constant so something like
would succeed (or fail if it wasn't equal).
ndim is correct regarding the executable or function in the first example you gave.
A couple more variations to consider:
In that one, the
if
is evaluated based on the return value of a command (executable or function) that is contained in the variableIsServerStarted
. So you could setIsServerStarted=true
and then theif
would succeed sincetrue
is a shell builtin that always returns true. You could setIsServerStarted='grep popsicle freezer' and the
if` would pass or fail depending on whether you were out of treats.This simply tests whether the variable is equal to zero. If it's not a valid integer it will cause an error message.