Test if a variable is set in bash when using “set -o nounset”

前端 未结 6 1715
北海茫月
北海茫月 2020-12-07 13:28

The following code exits with a unbound variable error. How to fix this, while still using the set -o nounset option?

#!/bin/bash

set -o nounse         


        
6条回答
  •  不思量自难忘°
    2020-12-07 13:38

    While this isn't exactly the use case asked for above, I've found that if you want to use nounset (or -u) the default behavior is the one you want: to exit nonzero with a descriptive message.

    It took me long enough to realize this that I figured it was worth posting as a solution.

    If all you want is to echo something else when exiting, or do some cleanup, you can use a trap.

    The :- operator is probably what you want otherwise.

提交回复
热议问题