BASH:[ ](测试)行为不一致
在我的 bash test
中有一种以状态 0
退出的态度:
$ test -n && echo true || echo false
-> true
而
$ test -n "" && echo true || echo false
-> false
这意味着当它根本没有收到任何参数时,它假设非零。
相反,情况 -z
可以正常工作:
$ test -z && echo true || echo false
-> true
$ test -z "" && echo true || echo false
-> true
这是预期的行为吗?
In my bash test
has an attitude to exit with status 0
:
$ test -n && echo true || echo false
-> true
while
$ test -n "" && echo true || echo false
-> false
It means when it doesn't receive any argument at all, it assumes nonzero.
The case -z
works properly instead:
$ test -z && echo true || echo false
-> true
$ test -z "" && echo true || echo false
-> true
Is this the expected behavior?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
基本上,您要询问测试字符串“-z”是否为非空。是的,所以它告诉你
true
。实际测试使用的算法是:引用自POSIX 测试命令规范。
Basically, you are asking test whether the string "-z" is nonempty. It is, so it tells you
true
. The actual algorithm test uses is:Quoted from the POSIX test command specification.
据推测,如果没有参数,“-n”和“-z”不会被视为运算符,而只是被视为字符串,并且
test“a non-empty string”
为 true。我猜想test
将其参数计数作为第一步,如果计数为 1,则只需检查参数的长度。Presumably, without arguments "-n" and "-z" are not treated as operators but as mere strings, and
test "a non-empty string"
is true. I would guess thattest
counts its arguments as a first step, and if the count is 1, simply examine the length of the argument.是的,这是预期的。
test [option] #without any operand
返回对所有选项均正确的退出状态。尝试以下操作:
Yes it is expected.
test [option] #without any operand
returns an exit status that is true for ALL options.Try these: