Bash 中的空和空字符串比较
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21407235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Null & empty string comparison in Bash
提问by logan
I don't set any values for $pass_tc11; so it is returning null while echoing. How to compare it in if
clause?
我没有为 $pass_tc11 设置任何值;所以它在回显时返回 null。如何在if
子句中进行比较?
Here is my code. I don't want "Hi" to be printed...
这是我的代码。我不想打印“嗨”...
-bash-3.00$ echo $pass_tc11
-bash-3.00$ if [ "pass_tc11" != "" ]; then
> echo "hi"
> fi
hi
-bash-3.00$
回答by fedorqui 'SO stop harming'
First of all, note you are not using the variable correctly:
首先,请注意您没有正确使用变量:
if [ "pass_tc11" != "" ]; then
# ^
# missing $
Anyway, to check if a variable is empty or not you can use -z
--> the string is empty:
无论如何,要检查变量是否为空,您可以使用-z
--> 字符串为空:
if [ ! -z "$pass_tc11" ]; then
echo "hi, I am not empty"
fi
or -n
--> the length is non-zero:
或-n
--> 长度非零:
if [ -n "$pass_tc11" ]; then
echo "hi, I am not empty"
fi
From man test
:
来自man test
:
-z STRING
the length of STRING is zero
-n STRING
the length of STRING is nonzero
-z 字符串
STRING 的长度为零
-n 字符串
STRING 的长度非零
Samples:
样品:
$ [ ! -z "$var" ] && echo "yes"
$
$ var=""
$ [ ! -z "$var" ] && echo "yes"
$
$ var="a"
$ [ ! -z "$var" ] && echo "yes"
yes
$ var="a"
$ [ -n "$var" ] && echo "yes"
yes
回答by espr
fedorqui has a working solution but there is another way to do the same thing.
fedorqui 有一个可行的解决方案,但还有另一种方法可以做同样的事情。
Chock if a variable is set
如果设置了变量,则阻塞
#!/bin/bash
amIEmpty='Hello'
# This will be true if the variable has a value
if [ $amIEmpty ]; then
echo 'No, I am not!';
fi
Or to verify that a variable is empty
或验证变量是否为空
#!/bin/bash
amIEmpty=''
# This will be true if the variable is empty
if [ ! $amIEmpty ]; then
echo 'Yes I am!';
fi
tldp.org has good documentation about if in bash:
http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html
tldp.org 有关于 if in bash 的很好的文档:http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html