If myvar is null or unset then it will be set to “notset”.
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.
4 Responses to “Bash: test for undefined variable”
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!)
July 23rd, 2008 at 8:32 pm
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
$
October 7th, 2008 at 6:00 pm
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’
October 22nd, 2008 at 9:06 pm
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!)
November 25th, 2008 at 10:23 pm
Thanks, this helped me a lot!