Bash If 语句为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19161112/
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
Bash If statement null
提问by Tony
Looking for the correct syntax that looks at a bash variable and determines if its null, if it is then do ... otherwise continue on.
寻找查看 bash 变量并确定其是否为空的正确语法,如果为空,则执行...否则继续。
Perhaps something like if [ $lastUpdated = null?; then... else...
也许像 if [ $lastUpdated = null?; then... else...
回答by trojanfoe
Just test if the variable is empty:
只需测试变量是否为空:
if [ -z "$lastUpdated" ]; then
# not set
fi
回答by Gordon Davisson
Expanding on @chepner's comments, here's how you could test for an unset (as opposed to set to a possibly empty value) variable:
扩展@chepner 的评论,这里是如何测试未设置(而不是设置为可能的空值)变量的方法:
if [ -z "${lastUpdated+set}" ]; then
The ${variable+word}
syntax gives an empty string if $variable
is unset, and the string "word" if it's set:
该${variable+word}
如果语法给出了一个空字符串$variable
没有设置,和字符串“字”,如果它的设置:
$ fullvar=somestring
$ emptyvar=
$ echo "<${fullvar+set}>"
<set>
$ echo "<${emptyvar+set}>"
<set>
$ echo "<${unsetvar+set}>"
<>
回答by panepeter
To sum it all up: There is no real nullvalue in bash. Chepner's comment is on point:
总而言之:bash 中没有真正的空值。Chepner 的评论是重点:
The bash documentation uses null as a synonym for the empty string.
bash 文档使用 null 作为空字符串的同义词。
Therefore, checking for null would mean checking for an empty string:
因此,检查 null 意味着检查空字符串:
if [ "${lastUpdated}" = "" ]; then
# $lastUpdated is an empty string
fi
If what you really want to do is check for an unset or empty(i.e. "", i.e. 'null') variable, use trojanfoe's approach:
如果您真正想要做的是检查未设置或空(即“”,即 ' null')变量,请使用 trojanfoe 的方法:
if [ -z "$lastUpdated" ]; then
# $lastUpdated could be "" or not set at all
fi
If you want to check weather the variable is unset, but are fine with empty strings, Gordon Davisson's answer is the way to go:
如果您想检查天气变量未设置,但对空字符串没问题,Gordon Davisson 的答案就是要走的路:
if [ -z ${lastUpdated+set} ]; then
# $lastUpdated is not set
fi
(Parameter Expansionis what's going here)
(参数扩展是这里发生的事情)