bug-bash
[Top][All Lists]
Advanced

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

Re: bug related to "set -e", "&&" and exit codes


From: Greg Wooledge
Subject: Re: bug related to "set -e", "&&" and exit codes
Date: Tue, 11 Feb 2025 09:18:53 -0500
User-agent: Mutt/1.10.1 (2018-07-13)

On Tue, Feb 11, 2025 at 08:48:25 +0100, Nagy László Zsolt wrote:

>  * The exit code of01b.shshould be 127 but in reality it is zero

So, you think 01b.sh is the one that's misbehaving?  OK, I can skip over
01a.sh then.

> *01b.sh*
> 
> #!/bin/bash
> set -e
> 
> echo "01b - 1 "
> ./02.sh && echo "You will not see this"
> echo "01b - 2 "

Assuming stdout isn't closed or something, this script should write
"01b - 1 " and then whatever ./02.sh writes and then "01b - 2 ", and
exit with status 0.

The second-to-last line has an && in it, so the set -e will not be
triggered by that line no matter how hard ./02.sh fails.  The only
way set -e could trigger on that line would be if the echo fails.

> > An AND list has the form
> >
> >               command1 && command2

> >
> >        command2  is  executed  if,  and only if, command1 returns a
> non-zero exit status. *The return status of AND and OR lists is the exit
> status of the last*

Ahh... I think I'm starting to see where your confusion is coming from.
You perhaps think that set -e should trigger on the ./02.sh failure
because the echo isn't executed.  But that's irrelevant.

Look at the definition of set -e:

             -e      Exit  immediately  if a pipeline (which may consist of a
                     single simple command), a list, or  a  compound  command
                     (see SHELL GRAMMAR above), exits with a non-zero status.
                     The shell does not exit if the  command  that  fails  is
                     part  of  the command list immediately following a while
                     or until keyword, part of the test following the  if  or
                     elif  reserved  words, part of any command executed in a
                     && or || list except the command following the final  &&
                     or ||, any command in a pipeline but the last, or if the
                     command's return value is being inverted with !.

In this case, the "command that fails" (./02.sh) is part of a && list, and
is not the final command in that list.  So, it can't trigger set -e.

At the risk of sounding like a broken record, set -e is *not* intuitive.
It doesn't work the way you expect.  It has a convoluted and ever-shifting
definition with lots of surprises.  Using set -e is a bad idea.  Your
scripts will be greatly improved if you stop using it.



reply via email to

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