在bash中,我怎么测试一个变量定义在" -u"模式 [英] In Bash, how do I test if a variable is defined in "-u" mode
问题描述
我刚刚发现设置-u
在bash和它帮助我pviously找到几个$ P $看不见的错误。但我也有一种情况,我需要测试变量是否计算了一些默认值之前定义。我想出了这个最好的是:
I just discovered set -u
in bash and it helped me find several previously unseen bugs. But I also have a scenario where I need to test if a variable is defined before computing some default value. The best I have come up with for this is:
if [ "${variable-undefined}" == undefined ]; then
variable="$(...)"
fi
该作品(只要变量没有字符串值未定义
)。我在想,如果有一个更好的办法?
which works (as long as the variable doesn't have the string value undefined
). I was wondering if there was a better way?
推荐答案
您可以测试在几个方面不确定的字符串。使用标准的测试条件是这样的:
What Doesn't Work: Test for Zero-Length Strings
You can test for undefined strings in a few ways. Using the standard test conditional looks like this:
# Test for zero-length string.
[ -z "$variable" ] || variable='foo'
这不会与工作设置-u
,但是。
另外,你可以使用条件的分配,这是一个更bash类似的方式来做到这一点。例如:
Alternatively, you can use conditional assignment, which is a more Bash-like way to do this. For example:
# Assign value if variable is unset or null.
: "${variable:=foo}"
由于猛砸方法来处理这个前pression扩展,你可以放心地使用设置-u使用
没有得到一个击:变量:未绑定变量错误。
Because of the way Bash handles expansion of this expression, you can safely use this with set -u
without getting a "bash: variable: unbound variable" error.
这篇关于在bash中,我怎么测试一个变量定义在" -u"模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!