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

后端 未结 7 2026
傲寒
傲寒 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:08

    if [ "${var+SET}" = "SET" ] ; then
        echo "\$var = ${var}"
    fi
    

    I don't know how far back ${var+value} is supported, but it works at least as far back as 4.1.2. Older versions didn't have ${var+value}, they only had ${var:+value}. The difference is that ${var:+value} will only evaluate to "value" if $var is set to a nonempty string, while ${var+value} will also evaluate to "value" if $var is set to the empty string.

    Without [[ -v var ]] or ${var+value} I think you'd have to use another method. Probably a subshell test as was described in a previous answer:

    if ( set -u; echo "$var" ) &> /dev/null; then
        echo "\$var = ${var}
    fi
    

    If your shell process has "set -u" active already it'll be active in the subshell as well without the need for "set -u" again, but including it in the subshell command allows the solution to also work if the parent process hasn't got "set -u" enabled.

    (You could also use another process like "printenv" or "env" to test for the presence of the variable, but then it'd only work if the variable is exported.)

提交回复
热议问题