BASH:[](测试)的行为不正确 [英] BASH: [ ] (test) behaves unconformly

查看:248
本文介绍了BASH:[](测试)的行为不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的重击中,test的态度是退出,状态为0:

In my bash test has an attitude to exit with status 0:

$ test -n && echo true || echo false
-> true

同时

$ test -n "" && echo true || echo false
-> false

这意味着当它根本不接收任何参数时,它将假定为非零.

It means when it doesn't receive any argument at all, it assumes nonzero.

案例-z相反可以正常工作:

The case -z works properly instead:

$ test -z && echo true || echo false
-> true
$ test -z "" && echo true || echo false
-> true

这是预期的行为吗?

推荐答案

基本上,您是在询问测试字符串"-z"是否为非空.是的,所以它告诉您true.实际的算法测试使用的是:

Basically, you are asking test whether the string "-z" is nonempty. It is, so it tells you true. The actual algorithm test uses is:

  • 0个参数:

  • 0 arguments:

退出false(1).

Exit false (1).

1个参数:

如果$ 1不为null,则返回true(0);否则为0.否则,返回false.

Exit true (0) if $1 is not null; otherwise, exit false.

2个参数:

如果$ 1为'!',如果$ 2为null则退出,如果$ 2不为null则退出.

If $1 is '!', exit true if $2 is null, false if $2 is not null.

如果$ 1是一元主变量,则如果一元测试为true,则退出true,否则返回false 如果一元测试为假.

If $1 is a unary primary, exit true if the unary test is true, false if the unary test is false.

否则,将产生未指定的结果.

Otherwise, produce unspecified results.

...

引自 POSIX测试命令规范.

这篇关于BASH:[](测试)的行为不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆