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

后端 未结 7 1992
傲寒
傲寒 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 09:59

    In bash 4.2 and newer there is an explicit way to check whether a variable is set, which is to use -v. The example from the question could then be implemented like this:

    if [[ ! -v variable ]]; then
       variable="$(...)"
    fi
    

    See http://www.gnu.org/software/bash/manual/bashref.html#Bash-Conditional-Expressions

    If you only want to set the variable, if it is not already set you are probably better of doing something along these lines:

    variable="${variable-$(...)}"

    Note that this does not deal with a defined but empty variable.

提交回复
热议问题