Test for a Bash variable being unset, using a function

后端 未结 7 1314
逝去的感伤
逝去的感伤 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 11:57

    What you're looking for is indirection.

    assertNotEmpty() {
        : "${!1:? "$1 is empty, aborting."}"
    }
    

    That causes the script to abort with an error message if you do something like this:

    $ foo=""
    $ assertNotEmpty foo
    bash: !1:  foo is empty, aborting.
    

    If you just want to test whether foo is empty, instead of aborting the script, use this instead of a function:

    [[ $foo ]]
    

    For example:

    until read -p "What is your name? " name && [[ $name ]]; do
        echo "You didn't enter your name.  Please, try again." >&2
    done
    

    Also, note that there is a very important difference between an empty and an unset parameter. You should take care not to confuse these terms! An empty parameter is one that is set but just set to an empty string. An unset parameter is one that doesn't exist at all.

    The previous examples all test for empty parameters. If you want to test for unset parameters and consider all set parameters OK, whether they're empty or not, use this:

    [[ ! $foo && ${foo-_} ]]
    

    Use it in a function like this:

    assertIsSet() {
        [[ ! ${!1} && ${!1-_} ]] && {
            echo "$1 is not set, aborting." >&2
            exit 1
        }
    }
    

    Which only aborts the script when the parameter name you pass denotes a parameter that isn't set:

    $ ( foo="blah"; assertIsSet foo; echo "Still running." )
    Still running.
    $ ( foo=""; assertIsSet foo; echo "Still running." )
    Still running.
    $ ( unset foo; assertIsSet foo; echo "Still running." )
    foo is not set, aborting.
    

提交回复
热议问题