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

后端 未结 7 1926
傲寒
傲寒 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:11

    The answers above are not dynamic, e.g., how to test is variable with name "dummy" is defined? Try this:

    is_var_defined()
    {
        if [ $# -ne 1 ]
        then
            echo "Expected exactly one argument: variable name as string, e.g., 'my_var'"
            exit 1
        fi
        # Tricky.  Since Bash option 'set -u' may be enabled, we cannot directly test if a variable
        # is defined with this construct: [ ! -z "$var" ].  Instead, we must use default value
        # substitution with this construct: [ ! -z "${var:-}" ].  Normally, a default value follows the
        # operator ':-', but here we leave it blank for empty (null) string.  Finally, we need to
        # substitute the text from $1 as 'var'.  This is not allowed directly in Bash with this
        # construct: [ ! -z "${$1:-}" ].  We need to use indirection with eval operator.
        # Example: $1="var"
        # Expansion for eval operator: "[ ! -z \${$1:-} ]" -> "[ ! -z \${var:-} ]"
        # Code  execute: [ ! -z ${var:-} ]
        eval "[ ! -z \${$1:-} ]"
        return $?  # Pedantic.
    }
    

    Related: How to check if a variable is set in Bash?

提交回复
热议问题