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

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

    You need to quote the variables if you want to get the result you expect:

    check() {
        if [ -n "${WHATEVER-}" ]
        then
            echo 'not empty'
        elif [ "${WHATEVER+defined}" = defined ]
        then
            echo 'empty but defined'
        else
            echo 'unset'
        fi
    }
    

    Test:

    $ unset WHATEVER
    $ check
    unset
    $ WHATEVER=
    $ check
    empty but defined
    $ WHATEVER='   '
    $ check
    not empty
    

提交回复
热议问题