Lessons · Terminal · errors do not go down the pipe
Errors do not go down the pipe
A plain | carries standard OUTPUT. Errors travel on a second stream and go straight to your screen, past every stage.
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 why a noisy command can still be the front of a pipeline, and why grepping for an error message finds nothing.
How to think about it
2>&1 before the pipe sends errors into the same stream. After the pipe it is too late and redirects the wrong thing.
Worked example
sh -c 'echo fine; echo broken 1>&2' > out.txtOnly 'fine' went into the file. 'broken' went to the screen.
cat out.txtOne line. The error was never in the stream.
sh -c 'echo fine; echo broken 1>&2' 2>&1 | grep brokenWith 2>&1 the error joins the stream and grep can see it.
Your turn
Send errors into the pipe as well as normal output.
ls missing.txt | grep missing
Try it at a real prompt
The trap
2>&1 has to come BEFORE the pipe. Written after it, it points stream 2 at wherever stream 1 goes in the NEXT command, which is not what you meant.
Practise errors do not go down the pipe on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.