Home > Mobile >  why ‘&&’ disables errexit(set -e)?
why ‘&&’ disables errexit(set -e)?

Time:08-05

consider script here:

set -e
make && make install
echo "SHOULD NOT BE HERE"

I expect that if make fails, the script will be aborted, but it's not:

make: *** No targets specified and no makefile found.  Stop.
SHOULD NOT BE HERE

But, if I changed it like this:

set -e
make 
make install
echo "SHOULD NOT BE HERE"

It works as expected:

make: *** No targets specified and no makefile found.  Stop.

Why this happens? Due to make && make install is commonly used in my build script, how should I use it correctly?

And please DO NOT link this question to Using set -e / set e in bash with functions, it's not the same question.

CodePudding user response:

Quoting from the answer to the question you linked:

Quoting sh(1) from FreeBSD, which explains this better than bash's man page:

 -e errexit
         Exit immediately if any untested command fails in non-interactive
         mode.  The exit status of a command is considered to be explicitly
         tested if the command is part of the list used to control an if,
         elif, while, or until; if the command is the left hand operand of
         an “&&” or “||” operator; or if the command is a pipeline preceded
         by the ! operator.  If a shell function is executed and its exit
         status is explicitly tested, all commands of the function are con‐
         sidered to be tested as well.

errexit exits only if an untested command fails. Using && (or ||) will means that bash considers the command to the left of && to be explicitly tested (which in turn means that it will not be handled by errexit).

See also here (specifically the part about list constructs).

As far a I know, there is no way to achieve what you would like by setting bash options.

  •  Tags:  
  • bash
  • Related