Test for a Bash variable being unset, using a function

后端 未结 7 1281
逝去的感伤
逝去的感伤 2020-12-07 11:37

A simple Bash variable test goes:

${varName:?    \"${varName} is not defined\"}

I\'d like to re-use this, by putting it in a function. How

相关标签:
7条回答
  • 2020-12-07 12:11

    You want to use [ -z ${parameter+word} ]

    Some part of man bash:

    Parameter Expansion
        ...
        In  each  of  the cases below, word is subject to tilde expansion, parameter expansion, command substitution, and
        arithmetic expansion.  When not performing substring expansion, bash tests for a parameter that is unset or null;
        omitting the colon results in a test only for a parameter that is unset.
        ...
        ${parameter:+word}
               Use Alternate Value.  If parameter is null or unset, nothing is substituted, otherwise  the  expansion  of
               word is substituted.
        ...
    

    in other words:

        ${parameter+word}
               Use Alternate Value.  If parameter is unset, nothing is substituted, otherwise  the  expansion  of
               word is substituted.
    

    some examples:

    $ set | grep FOOBAR
    $ if [ -z "${FOOBAR+something}" ]; then echo "it is unset"; fi
    it is unset
    $ declare FOOBAR
    $ if [ -z "${FOOBAR+something}" ]; then echo "it is unset"; fi
    $ FOOBAR=
    $ if [ -z "${FOOBAR+something}" ]; then echo "it is unset"; fi
    $ FOOBAR=1
    $ if [ -z "${FOOBAR+something}" ]; then echo "it is unset"; fi
    $ unset FOOBAR
    $ if [ -z "${FOOBAR+something}" ]; then echo "it is unset"; fi
    it is unset
    $
    
    0 讨论(0)
提交回复
热议问题