[fetchmail] if spoils $?

Matthias Andree matthias.andree@gmx.de
Thu, 28 Apr 2005 00:40:56 +0200


Steve Sheftic <kern0201@siscom.net> writes:

>> > if [ $? == 65 ] ; then
>> >   exit 0
>> > fi
>> > exit $?
>> 
>> This is bogus. 1. POSIX shells don't have ==, use = instead.
>> 2. The if [ ... spoils $?.
>
> Matthias,
>
> Are you sure about your #2? I use $? all the time in "if" constructs and
> it works for me. The following script (using sh on Solaris and bash on
> Linux) does not behave as though $? is being "spoiled".

Yes, I am sure. Explanation below.

Your  test (not quoted)  does not  refer to  what I  meant and  does not
reflect  the original  problem that  I  am quoting  again --  it has  no
relevance to the problem we're discussing.

Try this instead:

#! /bin/sh
set +e # don't barf on false
(exit 23)
if [ $? = 2 ] ; then
  echo "want 23, got 2, \$? is $?"
else
  echo "didn't get 2, \$? is $?"
fi
echo "want 23, got $?"

You'll see that the if itself resets  $? - which is no surprise, it runs
the  "[" command  with the  four arguments  "$?", "=",  "2" and  "]" and
branches depending on the exit code. Of course, the special parameter $?
gets reset by "[".

The "if"  itself resets  $? to 0,  unless it  executes the then  or else
branch, in that case the exit status of the branch remains set.

In the original construct, assume the  MDA's exit code were 67: the test
fails, setting $? to 1. If  has no else branch, so nothing gets executed
and $? gets reset to 0.

I know no solution for reusing the $? short of storing the contents $?
away in a variable right after the command that set it.

Shell programming is easy: $? gets set for EVERY pipeline (or command,
for that matter), including "test" and "[".

-- 
Matthias Andree