【发布时间】:2020-09-24 11:03:23
【问题描述】:
你好,我有一个简单的例子让我很困惑:
#!bin/bash
#test_str is a script to test whether a string is empty or not
x=''
if [ -n $x ]
then
echo "'$x' is not empty"
else
echo "'$x' empty"
fi
chmod u+x test_str
./test_str
输出:
'' is not empty
-
如果我没有声明变量(此处为 x),也会发生这种情况。
-
如果我使用标志
-z来测试是否为空,它可以正常工作:if [ -z $x ] then echo "'$x' is empty" else echo "'$x' not empty" fi
输出:
'' is empty
- 那么如何正确使用
-n呢? 谢谢!
【问题讨论】:
-
引用它!
[ -n "$x" ]没有它,构造被评估为[ -n ]这是总是 true -
重复的可能是stackoverflow.com/questions/6852612/… 搜索
-n时很难找到重复的:/ -
@Inian:请您解释一下。还是将其添加为答案?
-
@Inian:很好用,谢谢。最后一个问题:我是否也应该使用
""作为标志-z?如果不是,为什么? -
如有疑问,请务必查阅手册 - gnu.org/software/bash/manual/html_node/…。搜索
-z string和-n string