通常我只使用[[用于各种测试用例,因为它是最先进的方式,使用起来更安全(Regex,...)。 我知道[[执行不同的代码而不是[,但根据联机帮助页和各种文档,它至少应该处理像" -n"同样的方式,但它没有。
-n STRING STRING的长度为非零
class Animal: HandyJSON {
var name: String?
var id: String?
var num: Int?
required init() {}
}
let jsonString = "{\"name\":\"cat\",\"id\":\"12345\",\"num\":180}"
if let animal = JSONDeserializer<Animal>.deserializeFrom(jsonString) {
print(animal)
}
$ VAR为零
VAR=
if [[ -n $VAR ]]
then
echo "\$VAR is nonzero"
else
echo "\$VAR is zero"
fi
$ VAR非零
这怎么可能?
bash 4.1.2(1)
答案 0 :(得分:1)
我认为您的问题与报价有关。
使用[ -n $VAR ]
时,执行的命令不会包含$VAR
应该包含的任何参数:
$ set -x
$ [ -n $VAR ]
+ '[' -n ']'
这意味着您实际上在测试字符串-n
是否为非空,因为以下两个测试是等效的:
[ string ] # is a shorthand for
[ -n string ] # which is always true!
如果您使用引号,那么您会得到不同的行为:
$ [ -n "$VAR" ]
+ '[' -n '' ']'
现在您正在测试变量是否为非空,因此您可以获得预期的行为。
答案 1 :(得分:0)
Quoting。您必须引用在[
中使用的变量:
$ VAR=
$ [ -n $VAR ]
$ echo $?
0
$ [ -n "$VAR" ]
$ echo $?
1