|
发表于 2011-3-13 21:32:36
|
显示全部楼层
只是test命令的同义词。
Bash分析命令的时候,会首先做变量替换,然后才执行命令。
例如:
- str=""
- [ -n $str ] && echo true || echo false
复制代码
相当于:
- test -n $str && echo true || echo false
复制代码
而str为空,变量替换之后为空,由于没有放在引号里面,最后又会进行单词分割,于是得到
-
- test -n && echo true || echo false
复制代码
在Bash Manual中提到,当test命令有且仅有唯一一个不为空的参数时,总返回真值。这里唯一的参数是-n,所以这里返回true.
The test and [ builtins evaluate conditional expressions using a set of rules based on the number of arguments.
0 arguments
The expression is false.
1 argument
The expression is true if and only if the argument is not null.
至于"[["的结果为何不同。 这是因为"[["是Bash特殊的语法结构,不是test命令。 而且,双中括号里面不会进行单词分割,所以参数替换后的空值依然还在,能正确测试。
Word splitting and filename expansion are not performed on the words between the ‘[[’ and ‘]]’ Post by bzhao123;2130341
大家好!
我发现在shell里面: -n string 的命令必须放在[[]]里面才正常,放在 []里面不对的, 而-z string放在[]里面就正常,何解?我看manpage没明白。
谢! |
|