The head Command in Linux

We recently learned about the cat and the more commands in Linux. In this tutorial, we’ll be covering the head command which is pretty similar to the cat command in the essence that it helps you list down the contents of a file in the terminal. The head command has very few options, making this very straightforward and easy to use. Let’s begin!

How to use the head command in Linux

Similar to the cat command, the command format for the head command is head <options> <file names>. Let’s use the command with no options. I have a file with the numbers 1 to 15, each listed on individual lines. The default use should give us only the first 10 lines of the file.

root@HowLinux:~# head file1
Head Command Default Usage
Head Command Default Usage

1. Listing a specific number of lines using the head command in Linux

The -n option allows you to specify how many lines you want to print on the output. Let’s test it out by outputting only 3 lines instead of the default 10.

root@HowLinux:~# head -n 3 file1
Head N Option
Head N Option

2. Listing out file contents by specifying byte size

When using the head command in Linux, you also have the option to list out the contents of a file by the number of bytes. Now in the above example, each character has a specific number of bytes. What if we want to list the first few bytes of the file, we can make use of the -c option.

root@HowLinux:~# head -c 15 file1
1
2
3
4
5
6
7
8root@HowLinux:~#
Head C Option
Head C Option

As you can see, the last byte ended at number 8. So the new line character did not get printed and the bash prompt was printed right after the 8.

3. Quiet and Verbose options

When dealing with multiple files, the head command will list the names of the files before outputting their content to the terminal. But if you want to display the file name even if there’s just one file being outputted to the terminal, you can make use of the -v option. I’ll be limiting the output using the -n option so we can see the output on a single screen instead of needing to scroll.

root@HowLinux:~# head -v -n 3 file1
==> file1 <==
1
2
3
Head Verbose Option
Head Verbose Option

But on the opposite case scenario, if you do not want the head command output the have the names of the files, you can use the -q option to quiet the output. In this case, even if there you’re working with multiple files, the output will not have the file names. Let’s see an example of both the default output and output with the -q option.

root@HowLinux:~# head -n2 -q file1 file2
Head Quiet Option
Head Quiet Option

Conclusion

We covered all the options that the head command in Linux has. For quick reference in the future, I’ve created an infographic that lists down all the options that are available for the head command in Linux along with what they’re used for.

Head Command Options
Head Command Options