参见英文答案 >
Test for non-zero length string in Bash: [ -n “$var” ] or [ “$var” ]6个答案我没有为$ pass_tc11设置任何值;所以它在回显时返回null。如何在if子句中进行比较?
这是我的代码。我不希望打印“嗨”……
-bash-3.00$ echo $pass_tc11 -bash-3.00$ if [ "pass_tc11" != "" ]; then > echo "hi" > fi hi -bash-3.00$
首先,请注意您没有正确使用变量:
if [ "pass_tc11" != "" ]; then # ^ # missing $
无论如何,要检查变量是否为空,您可以使用-z – >字符串为空:
if [ ! -z "$pass_tc11" ]; then echo "hi,I am not empty" fi
或-n – >长度不为零:
if [ -n "$pass_tc11" ]; then echo "hi,I am not empty" fi
从男人测试:
-z STRING
the length of STRING is zero
-n STRING
the length of STRING is nonzero
样品:
$ [ ! -z "$var" ] && echo "yes" $ $ var="" $ [ ! -z "$var" ] && echo "yes" $ $ var="a" $ [ ! -z "$var" ] && echo "yes" yes $ var="a" $ [ -n "$var" ] && echo "yes" yes