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

Re: Test existence of shell variable, bash, csh



on Sat, May 05, 2001 at 04:08:26PM -0700, Eric G. Miller (egm2@jps.net) wrote:
> 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 "".
> > 
> > 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?
> 
> #! /bin/sh
> 
> ...
> 
> if test -z ${MYVAR} ; then
> 	...
> fi
> 
> The [...] shorthand isn't guaranteed AFAIK. Also, be sure variables are
> always "declared" first, at least like:
> 
> MYVAR = ""
> 
> Some bourne shells don't like testing variables that don't exist yet.

That's precisely what we're trying to test.

-- 
Karsten M. Self <kmself@ix.netcom.com>    http://kmself.home.netcom.com/
 What part of "Gestalt" don't you understand?       There is no K5 cabal
  http://gestalt-system.sourceforge.net/         http://www.kuro5hin.org

Attachment: pgpDe_uGTAk6K.pgp
Description: PGP signature


Reply to: