Bash: test for undefined variable

echo -n “myvar=${myvar:-notset}”

If myvar is null or unset then it will be set to “notset”.


4 Responses to “Bash: test for undefined variable”

  1. Anonymous Says:

    defined()
    {
    [ ${!1-X} == ${!1-Y} ]
    }

    Example:
    $ defined FOO || echo notset
    notset
    $ FOO=X
    $ defined FOO || echo notset
    $ FOO=
    $ defined FOO || echo notset
    $ unset FOO
    $ defined FOO || echo notset
    notset
    $ defined BASH_VERSION[2] || echo notset
    $ defined BASH_VERSION[20] || echo notset
    notset
    $

  2. ChrisGarrod Says:

    Thanks for both bits of info. I really like function defined, but don’t understand how it works. !1 ?? very curious. By the way, on my BASH, only BASH_VERSINFO is an array:

    # 10:56:58 garrod@sioprism 2.15 $ cd ~ && set | grep BASH
    BASH=/bin/bash
    BASH_VERSINFO=([0]=”2″ [1]=”05b” [2]=”0″ [3]=”1″ [4]=”release” [5]=”ia64-redhat-linux-gnu”)
    BASH_VERSION=’2.05b.0(1)-release’

  3. Rob Says:

    It works even better with some double quotes. Try this:

    defined()
    {
    [ “${!1-one} == “${!1-two}” ]
    }

    By way of explanation, it uses three bash expansions. First, you get the arguments to a function via ${1}. Second, you get indirection by adding the bang. ${!a} returns the value of the variable named by a. Third, it uses default values, just like your original code. I usually use “one” and “two” instead of “X” and “Y”. It doesn’t mater, so long as the values are different.

    (I wasn’t the previous commiter. I’m very indebted to both the original post and the previous comment. It was very helpful to me!)

  4. Sven Says:

    Thanks, this helped me a lot!

Leave a Reply