Interview Prep/Shell Scripting/Functions, exit codes, strict mode and traps

How does `pipefail` interact with `head`, `grep -q` and SIGPIPE?

AdvancedConceptFunctions, exit codes, strict mode and traps
Answer

When a reader exits early (head -1, grep -q), the writer gets SIGPIPE on its next write and dies with status 141 (128+13). With pipefail, the pipeline then fails even though you got the answer you wanted.

set -o pipefail
yes | head -n1; echo "${PIPESTATUS[@]}"   # 141 0 -> pipeline status 141

first_pod=$(kubectl get pods -o name | head -n1)   # may fail randomly on large output

Fixes: have the producer limit its own output where it can (--max-items, --limit, -m1), read everything first and then slice (mapfile -t pods < <(kubectl get pods -o name); first=${pods[0]}), or tolerate 141 explicitly for that one pipeline: { yes | head -n1; } || (( PIPESTATUS[0] == 141 )).

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Functions, exit codes, strict mode and traps