[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Test existence of shell variable, bash, csh



Lo, on Saturday, May 5, Ethan Benson did write:

> 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.  

I wondered about this a while back myself, and eventually asked on
comp.unix.shell.  In general, this is ok, but if $MYVAR's value is, say, !,
then you can get into some problems because of the way variable expansion
works in the shell.

A better solution, if you know for sure that you're using bash v2, is to
use something like

    if [[ -z "$MAIL" ]]; then ... fi;

where the double braces suppress some of the more unfortunate (in this
case) kinds of expansion.  (I think bash got this trick from ksh.)

Check the bash man page for more details, although be aware that it's not
entirely correct about which kinds of expansion are performed.

Richard



Reply to: