Bash error: Broken pipe (SIGPIPE)

Bash "Broken pipe" errors fire when a downstream command in a pipeline closes early. Often safe to ignore; handle with PIPESTATUS or `head`-aware producers.

Error String

bash: write error: Broken pipe

Tldr

A "Broken pipe" warning means the program writing to the pipeline tried to write after the reader closed. It is normal when piping into `head`, `grep -q`, or anything that exits early. To suppress it, use `head -c` carefully, trap SIGPIPE, or accept the harmless exit code.

Cause

When the reader of a pipe exits before the writer is done, the kernel sends SIGPIPE to the writer. The default action is to terminate; many programs (Python, especially) print "Broken pipe" before exiting.

Repro

yes | head -1                  # head exits after 1 line; yes gets SIGPIPE

Fix

# Option 1: accept it — it usually doesn't indicate a bug
yes | head -1 2>/dev/null

# Option 2: use PIPESTATUS to inspect each command's status
yes | head -1
echo "yes exit: ${PIPESTATUS[0]}  head exit: ${PIPESTATUS[1]}"

# Option 3: trap SIGPIPE in producers you control
trap '' PIPE

Explanation

In shell scripts the pipe failure is usually intentional. Use `set -o pipefail` only when an upstream failure should fail the whole pipeline, and ignore SIGPIPE on the producer in that case.

Faq

Q

Why did this only start after adding pipefail?

A

Without pipefail the pipeline reports the consumer status, which was zero. Pipefail surfaces the producer SIGPIPE as 141.

Q

Can I suppress SIGPIPE in the producer?

A

You can `trap "" PIPE`, but the write will then fail with EPIPE instead; handling the expected exit status is cleaner.

Deep Dive

Heading

The reader closed first

Body

When a consumer such as `head`, `less` or a `grep -q` exits after it has what it needs, the producer's next write hits a pipe with no reader and the kernel sends SIGPIPE, giving exit status 141. This is normal, expected behaviour for `producer | head -5`. It becomes visible only when `set -o pipefail` is on, because the pipeline then reports the producer failure the shell would otherwise ignore.

Heading

Deciding whether to care

Body

If early termination is intended, scope the tolerance to that pipeline: `{ producer || [ $? -eq 141 ]; } | head -5`, or drop `head` in favour of an option that stops the producer itself (`grep -m 5`, `find -quit`, `awk 'NR>5{exit}'`). If the broken pipe is unexpected, the consumer probably crashed — check its stderr and exit status before treating the message as noise. Python and other runtimes ignore SIGPIPE by default and surface it as an exception instead, which is why the same pipeline reports differently depending on the tools involved.

Checklist

Identify which side of the pipe exited first.

Treat 141 after `head`/`less` as expected termination.

Prefer producer-side limits (`grep -m`, `find -quit`) over killing the writer.

Investigate the consumer when the early exit was not intended.