Bash: test for undefined variable

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

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


Tags: ,

8 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!

  5. Panos says:

    This suffices:

    defined() {
    [[ ! -z "${1}" ]]
    }

    $ defined “${SOMEVAR}” || echo “notset”
    notset
    $ export SOMEVAR=”sometext”
    $ defined “${SOMEVAR}” || echo “notset”

  6. Jochen says:

    Not it doesn’t suffice.

    $ defined “${SOMEVAR}” || echo “notset”
    notset
    $ export SOMEVAR=”sometext”
    $ defined “${SOMEVAR}” || echo “notset”
    $ export SOMEVAR=
    $ defined “${SOMEVAR}” || echo “notset”

    It’ll show “notset” when a variable is defined but empty.

    -z only tells you whether a variable has content, not whether it’s set or not.

  7. Jochen says:

    Ugh of course I cut off the bottom line in the paste.

    $ export SOMEVAR=
    $ defined “${SOMEVAR} || echo “notset”
    notset

  8. Niranjan says:

    A VAR could take on teh following values:

    VAR=
    VAR=”" (Same as above)
    VAR=” “, and
    VAR=”something” (which is same as #3, VAR=” “)

    The solution has to defend against all these options.

    Assuming (Big assumption) that VAR’s value is always greater than a single alpha-numeric, one can test for the length of VAR.

Leave a Reply