加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

shell – 如何检查环境变量是否使用’set -o nounset’设置?

发布时间:2020-12-16 01:58:14 所属栏目:安全 来源:网络整理
导读:在bash / zsh中,以下检查变量的检查不起作用: #!/bin/zshset -o nounset # Error when unset vars are usedset -o errexit if [ -n ${foo-x} ]; then echo "Foo exists!"else echo "Foo doesn't exist"fi 因为即使foo不存在,foo也会被扩展,因此会触发,并且
在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和errexit,所以每次我想检查是否设置了var时,我宁愿不要中途禁用它们.

解决方法

您可以为检查创建一个函数(并且仅在函数中转动一个名词集),使用变量名称调用函数并使用间接变量引用.像下一个:

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"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读