Skip to content
Latchkey

head -n: First N Lines of Output

head -n N prints the first N lines and stops, the standard way to peek at the top of a stream.

head is how you take the top of sorted output or sample a file. The -n flag controls how many lines.

What it does

head -n N writes the first N lines of each input and exits. With a negative argument, head -n -N prints all but the last N lines. Given multiple files it prints a == filename == header before each unless you pass -q.

Common usage

Terminal
head -n 20 file.log
sort -nr counts.txt | head -n 5       # top 5
head -n -1 file.txt                   # all but the last line
head -n 100 *.log                     # first 100 of each, with headers

Options

FlagWhat it does
-n NPrint the first N lines
-n -NPrint all but the last N lines
-c NPrint the first N bytes instead of lines
-qNever print filename headers
-vAlways print filename headers

In CI

sort ... | head -n N is the standard top-N idiom. When head closes the pipe early it sends SIGPIPE to the upstream command, which usually exits cleanly, but a tool that ignores SIGPIPE can keep running and waste time.

Common errors in CI

The negative form head -n -N (all but last N) is GNU; BSD/macOS head rejects -n with a negative value, so that idiom fails on macOS runners. With set -o pipefail, the SIGPIPE that head triggers upstream can surface as a non-zero pipeline exit; account for it when gating on exit codes.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →