How to Use the head Command to Read the Beginning of a File in Linux

When working in the Linux terminal, you will frequently encounter massive log files or data sets that are thousands of lines long. If you just want to quickly check what kind of data is inside the file, or read the introductory comments of a script, opening the entire file in a text editor like nano or printing it all to the screen with cat is incredibly inefficient.

The head command is the perfect tool for this scenario. It allows you to peek at the very beginning of a file without loading the whole thing into memory.

The Basic head Command

By default, the head command is programmed to print exactly the first 10 lines of any file you point it at.

Syntax: head [filename]

For example, if you want to see the beginning of the system authentication log, you would open your terminal and type:

head /var/log/auth.log

Press Enter, and the terminal will output the first 10 lines and then immediately return you to the command prompt.

How to Read a Specific Number of Lines

Ten lines isn’t always enough. Sometimes you only want the very first line (like checking a CSV header), or perhaps you need to read the first 50 lines to understand a script.

You can change the default behavior by using the -n (number) flag followed by the exact number of lines you want.

Example 1: Read only the first line
head -n 1 data.csv

Example 2: Read the first 25 lines
head -n 25 setup.sh

How to View Multiple Files at Once

The head command is smart enough to handle multiple files simultaneously. If you want to check the beginning of three different configuration files to see how they differ, just list them one after another.

head -n 5 file1.txt file2.txt file3.txt

When you do this, Linux will helpfully print a small header before each chunk of text (e.g., ==> file1.txt <==) so you know exactly which lines belong to which file.

Using head with Pipes

Because it is a standard Linux utility, head works perfectly with pipes (|). This means you can take the massive output of another command and restrict it to just the top results.

For example, if you want to see the 5 largest files in a directory, you could sort the directory by size and then pipe the output directly into head:

ls -lS | head -n 5

This sorts the files (largest first) and the head command ensures your screen isn’t overwhelmed by only displaying the top 5 results, keeping your terminal clean and manageable.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.