help-bash
[Top][All Lists]
Advanced

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

Re: [Help-bash] When pipes fail (and when not)


From: Chet Ramey
Subject: Re: [Help-bash] When pipes fail (and when not)
Date: Wed, 28 Nov 2018 10:14:47 -0800
User-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:52.0) Gecko/20100101 Thunderbird/52.9.1

On 11/28/18 7:02 AM, Paul Wagner wrote:

> but installing another trap like
> 
> trap 'echo foo >&2' pipe
> for i in {0..9}; do echo $i; sleep 1; done | dd bs=1 count=10
> 
> ends after 5 iterations (so SIGPIPE is not trapped, but handled again), but
> does not write 'foo' to stderr (the terminal), and I don't understand why.

Each element of a pipeline is executed in a subshell environment, described
in

http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_12

"A subshell environment shall be created as a duplicate of the shell
environment, except that signal traps that are not being ignored shall be
set to the default action. [...] Additionally, each command of a multi-
command pipeline is in a subshell environment; as an extension, however,
any or all commands in a pipeline may be executed in the current
environment."

Subshell environments don't inherit traps from the parent shell, unless
the trap has specified that the signal is to be ignored. Bash always
executes the first element of a pipeline in a subshell environment.

If you define the trap in the same subshell environment as the for loop,
you'll get the output you want.

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



reply via email to

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