procmail
[Top] [All Lists]

Re: testing if a variable is EMPTY

1997-01-06 23:09:57
Timothy J Luoma <luomat(_at_)nerc(_dot_)com> writes:
I'd like to test if a variable has been set but has nothing as its  
contents.

I haven't been able to find any examples of this, but I'm sure it's  
a rather simple matter

All I want to do is:

if [ "$MyVar" = "" ]
then
      do this
else
      do that
fi

I don't know how to do that in procmailese.


Some testing with procmail 3.11pre4 shows the following works:

:0
* MyVar ?? ^^^^
{
    # do this
}
:0 E
{
    # do that
}

Note that if MyVar contains just a newline it'll be treated as non-empty
and "do that" will be executed.  If you want the "do this" part to be
executed when MyVar doesn't contain a non-newline character, then you
should use the alternative:

:0
* ! MyVar ?? .
{
    # do this
}
....etc


HOWEVER: both of those methods treat a variable set to nothing the same
as a variable that hasn't been set at all or that has been unset.  If
you want to tell apart those then you have to go to a lot of work, as
almost everything treats them the same.  I can think of two 'easy' ways
to do it: use perl, or provoke an error out of csh.

:0
* ! ? perl -e 'exit 1 unless exists $ENV{"MyVar"}'
{
    # MyVar is unset
}
:0 E
{
    # MyVar is set (possibly empty)
}

or

:0
* ! ? /bin/csh -c 'echo $MyVar' >/dev/null 2>&1
{
    # MyVar is unset
}
...etc

The latter of those is too slow and too much of a hack for general use,
so I'll explictly say that you shouldn't use it unless you lack perl,
in which case you should go out and install perl before using the hack.
And no, I won't explain why it works.

Anyway, the fact that doing this is so difficult should give you long
pause before you decide you need it.  You almost certainly don't, and
if you're sure you do, you consider using a separate flag variable
("MyVar_is_unset") to tell the differance when needed.  It'll probably
be clearer when you have to debug this all later, and it is certainly
faster.

Whew!  I have to stop drinking so much black tea...

Philip Guenther

<Prev in Thread] Current Thread [Next in Thread>