Lessons · Terminal · head and tail
The start and the end of a file
head -n 3 prints the first three lines; tail -n 3 prints the last three. tail -f keeps printing new lines as they arrive.
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
Logs are read from the end, data files are checked from the start, and a running server is watched with tail -f.
How to think about it
Ask which end you need. New things are at the end; the shape of a file shows at the start.
Worked example
printf '1\n2\n3\n4\n5\n' > n.txtFive lines.
head -n 2 n.txt1 and 2.
tail -n 2 n.txt4 and 5.
Your turn
Show the last 20 lines of app.log.
-n 20 app.log
Try it at a real prompt
The trap
head without -n prints ten lines by default, so a nine-line file looks like the whole thing was asked for.
Practise head and tail on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.