On Sat, May 05, 2001 at 02:34:47PM -0700, Karsten M. Self wrote:
> This came up on another list. The problem involves testing existence of
> a Unix shell variable from another program with limited system
> interaction features.
>
> I usually write this in bash as:
>
> if [ x${MYVAR} = x ]; then
> echo 'MYVAR doesn't exist (or isn't set)'
> else echo "MYVAR exists, value: $MYVAR"
> fi
>
> ...which essentially checks whether or not the variable has a non-null
> value. But would report that $MYVAR doesn't exist if in fact it was set
> equal to "".
i've personally always found this syntax utterly hideous, i also have
not really understood its justification over say:
if [ -n "$MYVAR" ] ; then
echo "MYVAR is set"
fi
i have used this syntax for quite awhile and have yet to encounter
problems, maybe test -n is not portable i don't think so though.
man test says -n tests whether the string is not null, whereas -z
tests that the string is null. you can also get away with:
if [ "$MYVAR" ] ; then
echo "MYVAR is set"
fi
but i suspect this is probably less safe.
> In contrast, csh and derivatives have:
>
> $?MYVAR
>
> ...which allows testing of presence of a variable.
>
> ...but I'm not aware of a similar bash/korn/bourne feature. Anyone?
see above.
--
Ethan Benson
http://www.alaska.net/~erbenson/
Attachment:
pgp3nEYc7FUww.pgp
Description: PGP signature