我想在 Ubuntu 22.04 中编写一个像这样工作的 bash 函数
Var1=100
is_variable_set "Var1" //Returns 0 (variable exists ie is set)
unset Var1
is_variable_set "Var1" //Returns 1 (variable does not exist ie is not set)
我目前的尝试没有奏效:
is_variable_set()
{
if [ -z "${1+some_string}" ]
then
echo "${1} is unset!"
return 1
fi
return 0
}
我尝试使用这个问题的方法: https://stackoverflow.com/questions/3601515/how-to-check-if-a-variable-is-set-in-bash
但无济于事:(
答案1
bash shell 实际上为此提供了一个内置测试。来自help test
:
Other operators: -o OPTION True if the shell option OPTION is enabled. -v VAR True if the shell variable VAR is set. -R VAR True if the shell variable VAR is set and is a name reference.
例如
$ var=
$ [[ -v var ]] && echo set || echo not set
set
$
$ unset var
$ [[ -v var ]] && echo set || echo not set
not set
答案2
我刚刚在 Google 上进行了更深入的搜索,看到了以下代码:
is_variable_set()
{
local -n refToCheck=$1
if [ -z "${refToCheck+some_string}" ]
then
echo "${1} is unset!"
return 1
else
echo "${1} is SET!"
return 0
fi
}
看起来运行良好:)