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

前端 未结 6 1713
北海茫月
北海茫月 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:36

    #!/bin/bash
    
    set -o nounset
    
    
    VALUE=${WHATEVER:-}
    
    if [ ! -z ${VALUE} ];
     then echo "yo"
    fi
    
    echo "whatever"
    

    In this case, VALUE ends up being an empty string if WHATEVER is not set. We're using the {parameter:-word} expansion, which you can look up in man bash under "Parameter Expansion".

提交回复
热议问题