我知道我可以使用-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我应该这样做
A is empty str is empty任何Linux专家都可以解释为什么?
谢谢。
I know i can test a string whether it is empty with -z and test a string whether it is non empty with -n. So I write a script in 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"To my surprise, it output :
A is empty A is non empty str is empty str is non emptywhich I thing it should be
A is empty str is emptyCould any Linux expert explain why ?
Thank you.
最满意答案
这是Bash命令行解析的结果。 变量替换在构造(基本)语法树之前发生,因此-n运算符不会将空字符串作为参数,它根本就没有参数 ! 一般来说,除非你能确定它不是空的,否则你必须把任何变量引用放入“”中,正是为了避免这种类似的问题
This is a consequence of the way Bash command lines are parsed. Variable substitution happens before constructing the (rudimentary) syntax tree, so the -n operator doesn't get an empty string as an argument, it gets no argument at all! In general, you must enclose any variable reference into "" unless you can be positively sure it isn't empty, precisely to avoid this and similar problems
更多推荐
发布评论