How can I make bash treat undefined variables as errors?

前端 未结 2 1391
被撕碎了的回忆
被撕碎了的回忆 2020-12-06 10:05

Please note: there are many questions about how to test a single shell variable on this site. This question is about testing a script for any undefined variable.

You

2条回答
  •  北荒
    北荒 (楼主)
    2020-12-06 10:22

    set -u is the more general option, but as pointed out in other answers' comments, there are problems writing idiomatic shell scripts with set -u in play. An alternative is to create parameter expansions that yield an error when a specific variable isn't set.

    $ echo $foo
    
    $ echo $?
    0
    $ echo "${foo?:no foo for yoo}"
    bash: foo: :no foo for yoo
    $ echo $?
    1
    

    This error will cause a non-interactive shell to exit. This gives you a quick way to guarantee an error condition won't allow control flow to continue with an undefined value. The spec does not require an interactive shell to exit, although it's worth noting that even in an interactive shell, bash will return from a function call if this error occurs in a function.

提交回复
热议问题