如this answer中所述,检查变量是否在bash中设置的“正确”方式如下所示:
if [ -z ${var+x} ]; then
echo "var is unset"
else
echo "var is set to '$var'"
fi
我感兴趣的是如何将其提取到一个可以重用于不同变量的函数中。
迄今为止我能做的最好的事情是:
is_set() {
local test_start='[ ! -z ${'
local test_end='+x} ]'
local tester=$test_start$1$test_end
eval $tester
}
它似乎有效,但有没有更好的方法不诉诸eval
?
答案 0 :(得分:4)
在Bash中,您可以使用[[ -v var ]]
。不需要功能或复杂的方案。
从联系手册:
-v varname True if the shell variable varname is set (has been assigned a value).
前2个命令序列打印ok
:
[[ -v PATH ]] && echo ok
var="" ; [[ -v var ]] && echo ok
unset var ; [[ -v var ]] && echo ok
答案 1 :(得分:1)
使用[[ ... ]]
,您只需执行此操作(不需要双引号):
[[ $var ]] && echo "var is set"
[[ $var ]] || echo "var is not set or it holds an empty string"
如果你真的想要一个函数,那么我们就可以编写单行代码:
is_empty() { ! [[ $1 ]]; } # check if not set or set to empty string
is_not_empty() { [[ $1 ]]; } # check if set to a non-empty string
var="apple"; is_not_empty "$var" && echo "var is not empty" # shows "var is not empty"
var="" ; is_empty "$var" && echo "var is empty" # shows "var is empty"
unset var ; is_empty "$var" && echo "var is empty" # shows "var is empty"
var="apple"; is_empty "$var" || echo "var is not empty" # shows "var is not empty"
最后,可以实施is_unset
和is_set
来将$1
视为变量的名称:
is_unset() { [[ -z "${!1+x}" ]]; } # use indirection to inspect variable passed through $1 is unset
is_set() { ! [[ -z "${!1+x}" ]]; } # check if set, even to an empty string
unset var; is_unset var && echo "var is unset" # shows "var is unset"
var="" ; is_set var && echo "var is set" # shows "var is set"
var="OK" ; is_set var && echo "var is set" # shows "var is set"