在 bash 中,为什么 if [ 1 ] 不会失败?
在 shell 脚本 (bash
) 中,为什么条件得到满足
if [ 1 ]
then
echo should not enter
fi
#Output
should not enter
In shell scripting (bash
) why does the conditional get satisfied
if [ 1 ]
then
echo should not enter
fi
#Output
should not enter
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
bash 中的方括号相当于使用括号内的参数调用
test
。man test
说和
,并且 1 不是空字符串。
if [ 0 ]
、if [ false ]
和if [ no ]
具有相同的结果,但if [ "" ]< /code> 还没有。
The square brackets in bash are equivalent to calling
test
with the arguments within the brackets.man test
says thatand
, and 1 is not an empty string.
if [ 0 ]
,if [ false ]
andif [ no ]
have the same result, butif [ "" ]
has not.可能不明显的是,这两者非常不同:
https://stackoverflow.com/questions/8108462/in-bash-why-does-if-1-not-fail
第一个,如 硫顿和Ignacio Vazquez-Abrams 说,隐式检查是否字符串
false
为空。第二个版本测试命令false
的退出状态。 (退出状态的测试实际上并不是真/假测试。它检查以数字代码表示的成功或失败。正如您可以想象的那样,false
的退出状态始终是失败。这就是它的工作。)有关所有这一切的更多信息,请参阅 BashGuide href="http://mywiki.wooledge.org/" rel="nofollow noreferrer">Greg 的 Wiki 非常清楚。
What may not be obvious is that these two are very different:
and
The first, as thiton and Ignacio Vazquez-Abrams say, implicitly checks if the string
false
is empty. The second version tests the exit status of the commandfalse
. (The testing of an exit status isn't literally a true/false test. It checks for success or failure as represented by numeric codes. As you can imagine, the exit status offalse
is always failure. That's its job.)For more on all of this, the BashGuide on Greg's Wiki is very clear.
因为
1
不是空字符串;它里面有一个字符,那就是数字“1”。Because
1
is not an empty string; it has one character in it, which is the numeral "1".