Bash: test for undefined variable
echo -n “myvar=${myvar:-notset}”
If myvar is null or unset then it will be set to “notset”.
Tags: bash, shell
This entry was posted
on Wednesday, August 1st, 2007 at 9:56 am and is filed under bash.
You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.
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
$
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’
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!)
Thanks, this helped me a lot!
This suffices:
defined() {
[[ ! -z "${1}" ]]
}
$ defined “${SOMEVAR}” || echo “notset”
notset
$ export SOMEVAR=”sometext”
$ defined “${SOMEVAR}” || echo “notset”
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.
Ugh of course I cut off the bottom line in the paste.
$ export SOMEVAR=
$ defined “${SOMEVAR} || echo “notset”
notset
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.