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

-- 
Eric G. Miller <egm2@jps.net>



Reply to: