在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是展开的,即使它不存在,nounset触发器也会退出。如何在不展开变量的情况下检查变量的存在性?我非常喜欢nounset和errexit,所以每次我想要检查是否设置了var时,我都不想半途而废。
发布于 2014-07-30 09:35:51
您可以为check (只在函数中转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+或zsh 5.3+)
[[ -v a ]] && echo "a ok" || echo "a no"
[[ -v b ]] && echo "b ok" || echo "b no"
[[ -v c ]] && echo "c ok" || echo "c no"https://stackoverflow.com/questions/25032910
复制相似问题