在bash / zsh中,检查变量的以下检查不起作用:
#!/bin/zsh
set -o nounset # Error when unset vars are used
set -o errexit
if [ -n ${foo-x} ]; then
echo "Foo exists!"
else
echo "Foo doesn't exist"
fi
因为即使foo不存在,foo也会被扩展,nounset会触发,并且它会退出。如何在不扩展变量的情况下检查变量的存在?我真的很喜欢nounset和errexit,所以每次我想检查是否设置了var时,我不想中途禁用它们。
答案 0 :(得分:1)
您可以为检查创建一个函数(并仅在函数中转动nounset
),使用变量名称调用函数并使用间接变量引用。类似下一个:
set -o nounset
set -o errexit
isset() {
set +o nounset
[[ -n "${!1+x}" ]]
result=$?
set -o nounset
return $result
}
a=1
#call the "isset" with the "name" not value, so "a" and not "$a"
isset a && echo "a is set" || echo "a isnt set"
b=''
isset b && echo "b is set" || echo "b isnt set"
isset c && echo "c is set" || echo "c isnt set"
打印:
a is set
b is set
c isnt set
刚刚学会了一个干净的方法,使用-v varname
(需要bash 4.2)
[[ -v a ]] && echo "a ok" || echo "a no"
[[ -v b ]] && echo "b ok" || echo "b no"
[[ -v c ]] && echo "c ok" || echo "c no"