空值Bash中的空字符串比较 [英] Null & empty string comparison in Bash
本文介绍了空值Bash中的空字符串比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我没有为$ pass_tc11设置任何值;因此它在回显时返回null.如何在 if
子句中进行比较?
I don't set any values for $pass_tc11; so it is returning null while echoing. How to compare it in if
clause?
这是我的代码.我不希望打印嗨" ...
-bash-3.00$ echo $pass_tc11
-bash-3.00$ if [ "pass_tc11" != "" ]; then
> echo "hi"
> fi
hi
-bash-3.00$
推荐答案
首先,请注意您没有正确使用变量:
First of all, note you are not using the variable correctly:
if [ "pass_tc11" != "" ]; then
# ^
# missing $
无论如何,要检查变量是否为空,可以使用 -z
->字符串为空:
Anyway, to check if a variable is empty or not you can use -z
--> the string is empty:
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
来自 man test
:
-z STRING
STRING的长度为零
the length of STRING is zero
-n STRING
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
这篇关于空值Bash中的空字符串比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文