bash空字符串比较问题(bash empty string comparison Issue)

编程入门 行业动态 更新时间:2024-10-26 20:27:45
bash空字符串比较问题(bash empty string comparison Issue)

我知道我可以使用-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 empty

which I thing it should be

A is empty str is empty

Could 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

更多推荐

本文发布于:2023-08-07 12:22:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464293.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:空字符串   empty   bash   Issue   comparison

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!