bash空字符串比较问题

3

我知道可以使用-z测试字符串是否为空,使用-n测试字符串是否非空。因此,我在Ubuntu 10.10中编写了一个脚本:

#!/bin/bash
A=
test -z $A && echo "A is empty"
test -n $A && echo "A is non empty"
test $A && echo "A is non empty" 

str=""
test -z $str && echo "str is empty"
test -n $str && echo "str is non empty"
test $str && echo "str is non empty" 

令我惊讶的是,它输出了:
A is empty
A is non empty
str is empty
str is non empty

我认为应该是这样的


与IT技术有关的内容
A is empty
str is empty

有没有Linux专家能解释一下为什么?

谢谢。

3个回答

5

这是Bash命令行解析的结果。变量替换发生在构建(基本)语法树之前,因此-n运算符不会得到空字符串作为参数,而是得到没有任何参数!通常情况下,除非您确信它不为空,否则必须将任何变量引用括在""中,以避免此类问题。


5
“问题”源于以下原因:
$ test -n && echo "Oh, this is echoed."
Oh, this is echoed.

即,没有参数的test -n返回0/ok。 改为:
$ test -n "$A" && echo "A is non empty"

并且您将获得您所期望的结果。


2
这个可以使用:
#!/bin/bash
A=
test -z "$A" && echo "A is empty"
test -n "$A" && echo "A is non empty"
test $A && echo "A is non empty" 

str=""
test -z "$str" && echo "str is empty"
test -n "$str" && echo "str is non empty"
test $str && echo "str is non empty"

只有 $A 或者 $str 为空字符串时,才不会成为测试的参数,此时测试状态总是 true,因为只有一个参数(非空字符串)。最后一行代码的作用是当没有参数时,测试结果总是 false。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接