Skip to content

Linux Foundations / Find your way around Linux ยท Step 38 of 63

Lesson: headSwitch
โ† Linux Foundations

Shell and files

head

Learn to look at the beginning of files and streams with head.

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/passwd

This 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
cherry

You 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
3

BSD and macOS versions may not support this.

Count bytes instead

-c prints a number of bytes.

$ echo "abcdefgh" | head -c 4
abcd

No 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 b

GNU head -q hides these headers.

In pipelines

head is often the last step, trimming a long result.

$ ls -t | head -n 5

This 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

  1. Run head /etc/services, if the file exists on your system.
  2. Run head -n 2 /etc/passwd.
  3. Run seq 100 | head -n 4.
  4. Run head -c 20 /etc/passwd and 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.