When a file is long, you often need only its first few lines to know what it is. head shows the beginning of a file and then stops.
The default is ten lines
$ head /etc/passwdThis prints the first 10 lines. If the file has fewer, you get all of them, with no error.
Choose how many lines
Use -n:
$ head -n 3 fruit.txt
apple
banana
cherryYou may see the older form head -3. It still works in common implementations, but -n 3 is the standard spelling.
GNU head, found on most Linux systems, also accepts a negative number to print everything except the last N lines:
$ seq 5 | head -n -2
1
2
3BSD and macOS versions may not support this.
Count bytes instead
-c prints a number of bytes.
$ echo "abcdefgh" | head -c 4
abcdNo newline follows abcd, because it was not among the first four bytes, so your prompt may appear on the same line. This is handy for peeking at a binary file's signature.
Several files
Given more than one file, head labels each part:
$ head -n 1 a.txt b.txt
==> a.txt <==
first line of a
==> b.txt <==
first line of bGNU head -q hides these headers.
In pipelines
head is often the last step, trimming a long result.
$ ls -t | head -n 5This shows the five most recently modified entries, since ls -t sorts newest first. Once head has what it needs, it exits, and the program feeding it is usually stopped the next time it tries to write.
The streams and text lab is a good place to practise.
Try it
- Run
head /etc/services, if the file exists on your system. - Run
head -n 2 /etc/passwd. - Run
seq 100 | head -n 4. - Run
head -c 20 /etc/passwdand note where it stops.
Check your understanding
head
All 5 sections ยท no timer
Unlimited retries
Questions from every section are combined into one assessment. Answer them all correctly to complete the article.
Your completion saves in this browser. Sign in to sync it to your account.