On Sat, Dec 13, 2025 at 13:53:09 +0100, Kye Hunter wrote:
> set -o pipefail
> wc --version | head -n 1 ; echo $? # returns 141 ~50% of the time
> wc --version | sed '1q' ; echo $?  # returns 141 very rarely, but it does
> happen

This is one of the main reasons why pipefail is *not* enabled by default,
and *should not* be enabled universally.  It might be acceptable in
specific situations where it's known in advance that no pipeline commands
should be terminated by SIGPIPE under normal conditions.  But as you've
stumbled across, there are countless perfectly valid pipelines where
a SIGPIPE happens naturally.

> The inconsistent behavior makes this seem like a race, perhaps, in the
> script below, head is trying to close the pipe before wc finishes writing to
> it, causing it to return the error.

Yes, it's a race condition that causes the variance in the results.
However, this is not a bug in bash or in wc.  The only error here was
using pipefail.

See also <https://mywiki.wooledge.org/BashPitfalls#pf60>.

Reply via email to