linux – bash空字符串比较问题
发布时间:2020-12-13 23:55:37 所属栏目:Linux 来源:网络整理
导读:我知道我可以使用-z测试字符串是否为空,并使用-n测试字符串是否为空.所以我在ubuntu 10.10中编写了一个脚本: #!/bin/bashA=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 e
我知道我可以使用-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专家解释原因吗? 谢谢. 解决方法
这是解析Bash命令行的方式的结果.变量替换在构造(基本)语法树之前发生,因此-n运算符不会将空字符串作为参数,它根本没有参数!通常,您必须将任何变量引用括在“”中,除非您可以肯定它不是空的,正是为了避免这种和类似的问题
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |