bug-bash
[Top][All Lists]
Advanced

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

Re: Exit status of "if" statement?


From: Barry Margolin
Subject: Re: Exit status of "if" statement?
Date: Tue, 10 Apr 2012 02:26:24 -0400
User-agent: MT-NewsWatcher/3.5.3b3 (Intel Mac OS X)

In article 
<address@hidden>,
 bsh <address@hidden> wrote:

> Janis Papanagnou <address@hidden> wrote:
> > Dan Stromberg wrote:
> > > What should be the behavior of the following?
> > > if cmd1
> > > then
> > >     cmd2
> > > fi && if cmd3
> > > then
> > >    cmd4
> > > fi
> 
> Hello Daniel and Janis!
> 
> > If cmd1 is true then execute cmd2;
> >   cmd2 defines the exit code for the first if
> > depending on cmd2 return value,
> >   if true then the subsequent if is executed
> >     if cmd3 is true then execute cmd4;
> >       cmd4 defines the exit code for the second if
> 
> I see a problem, which I cannot immediate test on a
> command line available to me now.
> 
> First of all, the manpage plainly indicates:
> 
> "Usage: if if-list;then list[;elif list;then list]... [;else list];fi
> ... If the if-list has a non-zero exit status and there is
> no else-list, then the if command returns a zero exit status."
> 
> > > Playing around, it appears that cmd1 and cmd3 have no
> > > direct impact on the exit codes of the two if's, while
> > > cmd2 and cmd4 do (if cmd1 or cmd3 evaluate true).
> > Yes. cmd1 and cmd3 control the if condition, and the resulting
> > exit code is defined by the last command executed, either cmd2
> > or cmd4.
> 
> ... And because of this, it is impossible to discern whether
> the return code is the result of a failed if-list or the
> last command in the if-body code. This strikes me as poor
> programming discipline.

If you care about the exit status of the if-list, run it separately and 
save it.  I.e. instead of:

if cmd1; cmd2; ...
then ...
fi

write:

cmd1; cmd2; ...
status=$?
if [ $status = 0 ]
then ...
fi

The assumption behind the design of "if" is that you only care about the 
success or failure of the if-list, not the specific kind of failure.

-- 
Barry Margolin, address@hidden
Arlington, MA
*** PLEASE post questions in newsgroups, not directly to me ***


reply via email to

[Prev in Thread] Current Thread [Next in Thread]