使用未设置与设置变量为空 [英] Using unset vs. setting a variable to empty
问题描述
我目前正在写一个bash测试框架,其中,在测试功能,包括标准的bash测试( [
),以及predefined匹配器可用过的。匹配器的包装为[['再说返回返回code,设置一些有意义的消息,说是预期。
I'm currently writing a bash testing framework, where in a test function, both standard bash tests ([[
) as well as predefined matchers can be used. Matchers are wrappers to '[[' and besides returning a return code, set some meaningful message saying what was expected.
例如:
string_equals() {
if [[ ! $1 = $2 ]]; then
error_message="Expected '$1' to be '$2'."
return 1
fi
}
因此,当使用一个匹配器,并且它出现故障,只有一个ERROR_MESSAGE设置
So, when a matcher is used, and it fails, only then an error_message is set.
现在,在某一时刻后,我测试的测试是否成功。如果成功,我打印的预期为绿色,如果用红色失败。
Now, at some point later, I test whether the tests succeeded. If it succeeded, I print the expectation in green, if it failed in red.
此外,还有可能是ERROR_MESSAGE集,所以我测试是否存在一个信息,打印出来,然后再取消它(因为下面的测试可能没有设置 ERROR_MESSAGE
):
Furthermore, there may be an error_message set, so I test if a message exists, print it, and then unset it (because the following test may not set an error_message
):
if [[ $error_message ]]; then
printf '%s\n' "$error_message"
unset -v error_message
fi
现在我的问题是,如果是更好地取消设置变量,或者只是将其设置为'',像
Now my question is, if it is better to unset the variable, or to just set it to '', like
error_message=''
哪一个更好?是否真正发挥作用?或者,也许我应该说明该消息已设定额外的标志?
Which one is better? Does it actually make a difference? Or maybe should I have an additional flag indicating that the message was set?
推荐答案
在一个环境变量方面,有一个空字符串,而不是设置没有区别:
In terms of an environment variables, there is no difference between an empty string and not set:
var=
和
var=""
产生同样的事情(Bash的手册页确认)。
produce the same thing (the Bash man pages confirm that).
使用取消设置
虽然实际上删除变量。大多看不到有区别的,除非你使用设置-u
:
Using unset
though actually deletes the variable. Mostly you don't see a difference, unless you are using set -u
:
/home/user1> var=""
/home/user1> echo $var
/home/user1> set -u
/home/user1> echo $var
/home/user1> unset var
/home/user1> echo $var
-bash: var: unbound variable
因此,其实这要看你如何去测试变量。
So really, it depends on how you are going to test the variable.
我要补充,我的$ P $测试pferred的方式,如果它被设置为:
I will add that my preferred way of testing if it is set is:
[[ -n $var ]] # True if not zero length
或
[[ -z $var ]] # True if zero length
我要补充一点,设置为空字符串,并使用取消设置
对数组完全不同的效果(我的猜测是不是这里的情况)。
I should add that setting to an empty string and using unset
have drastically different effects on arrays (which I guess is not the case here).
这篇关于使用未设置与设置变量为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!