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 )).
More on Functions, exit codes, strict mode and traps
How do you define a function, pass arguments and return a value?BeginnerWhat does `local` do, and what is dynamic scoping?AdvancedWhy is `local out=$(cmd)` a problem under `set -e`?AdvancedWhat are the conventional exit codes, and what do 126, 127, 130, 137 and 143 mean?BeginnerWhat does `set -e` do, and where does it NOT cause an exit?AdvancedExplain `set -euo pipefail` line by line, and add the `-E` flag.Beginner