Shell 如何检查环境变量是否设置为';集合-o名词集合'?

Shell 如何检查环境变量是否设置为';集合-o名词集合'?,shell,Shell,在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

在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时,我不想中途禁用它们。

您可以为检查创建一个函数(并且只在函数中旋转
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+)


@Nick添加了一个更简单、干净的方法,没有函数。
[[ -v a ]] && echo "a ok" || echo "a no"
[[ -v b ]] && echo "b ok" || echo "b no"
[[ -v c ]] && echo "c ok" || echo "c no"