When you need to view the contents of a text file in the Ubuntu terminal, the most common tool is the cat command, which dumps the entire file directly onto your screen. This works perfectly for small, 10-line configuration scripts. But what happens if you run cat on a server access log that contains 50,000 lines? The terminal will violently scroll for thirty seconds before finally stopping at the very bottom of the file, making it impossible to read the initial lines without tedious scrolling.
Often, you only need to see the very first few lines of a file—perhaps to check the column headers of a massive CSV dataset, or to read the comment block at the top of a shell script to see what it does.
Instead of opening the file in a heavy text editor like nano, you can use a lightweight, specialized tool called head. This guide explains how to use the head command to efficiently peek at the beginning of files in Linux.
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, and then immediately stop.
To view the first 10 lines of a file named server_logs.txt, type the command followed by the filename:
head server_logs.txt
The terminal will instantly print the first 10 lines to the screen and then gracefully drop you back to an empty command prompt, saving you from scrolling through thousands of irrelevant lines.
How to Change the Number of Lines
While 10 lines is a sensible default, you often need to see more or less data. You can easily override the default behavior by passing the -n (number) flag followed by the exact number of lines you want to extract.
For example, if you just want to see the very first line of a CSV file to determine what the data columns are named, you would run:
head -n 1 data_export.csv
Conversely, if you need to read a long introductory paragraph at the top of a configuration file, you could ask for the first 50 lines:
head -n 50 /etc/ssh/sshd_config
How to View Multiple Files Simultaneously
The head command is incredibly useful when you need to quickly identify the contents of several files at once. You can pass multiple filenames to the command separated by spaces.
head -n 3 file1.txt file2.txt file3.txt
When you do this, the terminal will neatly organize the output. It will print a small header featuring the name of the first file (e.g., ==> file1.txt <==), print the first three lines of that file, and then move on to create a new header for the second file. This is an extremely fast way to preview the contents of a directory without opening every file individually.
Pro Tip: If you need to view the end of a file instead of the beginning (for example, to see the most recent errors in an active log file), simply use the exact same syntax but replace the word head with the command tail.