As explained in this answer, the "right" way to check if a variable is set in bash looks like this:
if [ -z ${var+x} ]; then
echo "var is unset"
else
echo "var is set to '$var'"
fi
Run Code Online (Sandbox Code Playgroud)
What I'm interested in is how to extract this into a function that can be reused for different variables.
The best I've been able to do so far is:
is_set() {
local test_start='[ ! -z ${'
local test_end='+x} ]'
local tester=$test_start$1$test_end
eval $tester
}
Run Code Online (Sandbox Code Playgroud)
It seems to work, but is there a better way that doesn't resort to calling eval?
在 Bash 中,您可以使用[[ -v var ]]. 不需要函数或复杂的方案。
从联机帮助页:
Run Code Online (Sandbox Code Playgroud)-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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
475 次 |
| 最近记录: |