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: bsh
Subject: Re: Exit status of "if" statement?
Date: Mon, 9 Apr 2012 19:26:08 -0700 (PDT)
User-agent: G2/1.0

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.

BTW, the reason that the manpage keeps talking about command
"lists", instead of individual commands, is because the "if"
criterion is the return code of the _last_ command in a command
_list_. That is to say, the following is possible and even
recommended:

if    cmd1
      cmd2
      cmd3
then  ...
fi

It is the return code of cmd3 which determines the flow-of-
control. This construction reinforces readable and structured
localization of code.

> > Is this the defined behavior in POSIX shell?  In
> > bash?  In bash symlinked to /bin/sh? In dash?
> I think it is defined that way in all POSIX complient shells.

Yes:

POSIX XSH: (2.9.4) Compound Commands: The if Conditional Construct:
http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_04

"The exit status of the 'if' command shall be the exit status of
the 'then' or 'else' compound-list that was executed, or zero,
if none was executed."

=Brian


reply via email to

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