help-bash
[Top][All Lists]
Advanced

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

Re: ERR trap, pipeline, and errtrace


From: Chet Ramey
Subject: Re: ERR trap, pipeline, and errtrace
Date: Thu, 7 Jan 2021 15:40:47 -0500
User-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:78.0) Gecko/20100101 Thunderbird/78.6.0

On 1/7/21 2:23 AM, Boris Kolpackov wrote:

This script prints the following (tested with bash versions 4.3, 4.4,
and 5.0):

good
trap
failed

Is this behavior expected ? As you might have recognized, this is a
workaround for the infamous "set -e; if myfunc ..." issue[1].

Yes, it's expected.


The two relevant pieces of the documentation are the trap builtin and
errtrace (-E) (quoting only the relevant parts):

"
trap

   The ERR trap is not executed if the failed command is part of the
   command list immediately following an until or while keyword, part
   of the test following the if or elif reserved words, part of a
   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 status is being inverted using !. These are
   the same conditions obeyed by the errexit (-e) option.
"

"
-E

   If set, any trap on ERR is inherited by shell functions, command
   substitutions, and commands executed in a subshell environment.
   The ERR trap is normally not inherited in such cases.
"

In a way this behavior does make sense since I believe a pipeline is
considered a subshell. If it is indeed the expected behavior, perhaps,
this part of the trap documentation

"...any command in a pipeline but the last..."

Could be clarified along these lines:

"... any command in a pipeline but the last unless the errtrace (-E) option
  is specified ..."

The language is fine; it describes the default behavior of the ERR trap. In
the trap command description, the "any command in a pipeline" refers to the
function call, and indeed, the trap does not get run even though the exit
from the trap handler causes the pipeline element to return a non-zero
status.

The errtrace description correctly describes the fact that the shell function inherits the ERR trap because of the state of errtrace; the
fact of running the function in a pipeline does not change that, since
the shell simply forks when it creates the pipeline and doesn't do any
modifications to the subshell environment beyond what the man page
describes in the COMMAND EXECUTION ENVIRONMENT section.


--
``The lyf so short, the craft so long to lerne.'' - Chaucer
                 ``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, UTech, CWRU    chet@case.edu    http://tiswww.cwru.edu/~chet/



reply via email to

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