In Bash, how do I test if a variable is defined in “-u” mode

后端 未结 7 2017
傲寒
傲寒 2020-12-23 09:14

I just discovered set -u in bash and it helped me find several previously unseen bugs. But I also have a scenario where I need to test if a variable is defined

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-23 10:10

    Unfortunatly [[ -v variable ]] is not supported in older versions of bash (at least not in version 4.1.5 I have on Debian Squeeze)

    You could instead use a sub shell as in this :

    if (true $variable)&>/dev/null; then
        variable="$(...)"
    fi
    

提交回复
热议问题