Hone

Lessons · Terminal · a pipeline's code is the last stage's

A pipeline's exit code is the last stage's

$? after a pipeline holds the LAST command's code. A failure in the middle leaves no trace.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

It is how a broken pipeline passes a check and a script carries on.

How to think about it

set -o pipefail makes the pipeline take the first non-zero code instead.

Worked example

grep zzz access.log | wc -l; echo "code=$?"
wc succeeded, so the code is 0 even though grep found nothing.
grep zzz access.log; echo "code=$?"
On its own, grep reports 1: it matched nothing.
set -o pipefail; grep zzz access.log | wc -l; echo "code=$?"
With pipefail the pipeline reports grep's 1.

Your turn

Make a pipeline report the first failure, not the last stage.

set -o 

The trap

set -e alone does not help. Without pipefail it never sees a failure that happened before the final stage.

Practise a pipeline's code is the last stage's on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.