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

后端 未结 7 1977
傲寒
傲寒 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:54

    What Doesn't Work: Test for Zero-Length Strings

    You can test for undefined strings in a few ways. Using the standard test conditional looks like this:

    # Test for zero-length string.
    [ -z "$variable" ] || variable='foo'
    

    This will not work with set -u, however.

    What Works: Conditional Assignment

    Alternatively, you can use conditional assignment, which is a more Bash-like way to do this. For example:

    # Assign value if variable is unset or null.
    : "${variable:=foo}"
    

    Because of the way Bash handles expansion of this expression, you can safely use this with set -u without getting a "bash: variable: unbound variable" error.

提交回复
热议问题