If false; then
echo jj
fi
always has to return 0 otherwise a lot of code using ERREXIT/ERRTRACE
would break.
if you want to handle an error case you should use elif or else
your example could be written like this
if cmd1
then
cmd2
elif cmd3
then
cmd4
fi
or possibly like this
if cmd1
then
cmd2
else
if cmd3
then
cmd4
fi
fi
or if you wanted to be more cryptic
cmd1&& { cmd3 || true ; } || { cmd3&& cmd4 ; }
though it would be advisable to append a "|| true" to cmd2 and cmd4,
showing explicitly that you are ignoring the return value.
if cmd1
then
cmd2 || true
elif cmd3
then
cmd4 || true
fi
hth
John
Am 10.04.2012 04:26, schrieb bsh:
Janis Papanagnou<janis_papanag...@hotmail.com> 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