Hone

Lessons · Terminal · head stops a pipeline early

head stops the pipeline

head closes the pipe once it has what it asked for, and everything upstream is told to stop.

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 what makes peeking at a huge file instant instead of a minute.

How to think about it

At the FRONT of a pipeline head is a sample; at the END it is the top of an answer.

Worked example

head -n 3 access.log
The first three lines, and nothing read the rest.
sort access.log | head -n 2
sort must read it all to sort it, but the pipeline ends as soon as head is full.
head -n 2 access.log | sort
head at the front: everything after it only ever sees two lines.

Your turn

Take the last two lines of app.log.

 -n 2 app.log

The trap

Those last two commands look alike and answer different questions. Where head sits decides what the rest of the pipeline is allowed to see.

Practise head stops a pipeline early on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.