When you are managing a Linux server from the command line, opening a massive text file—such as a system log, an SQL database dump, or a dense configuration file—using a full text editor like nano or vim can be incredibly slow and inefficient, especially if you only need to check the file’s header or verify its format.
The head command is a core Linux utility specifically designed for this exact scenario. It allows you to quickly print the first few lines of any text file directly to your terminal screen, allowing you to safely preview the contents of a massive file without loading the entire document into system memory.
The Basic ‘head’ Command
By default, if you use the head command without any additional flags, it will print exactly the first 10 lines of the file.
- Open your terminal or SSH into your server.
- Type
headfollowed by the name (or absolute path) of the file you want to inspect. For example:
head /var/log/syslog
The terminal will instantly print the first 10 lines of the system log to your screen and immediately return you to the command prompt.
How to Change the Number of Lines
If 10 lines are not enough to understand the context of the file, or if you only want to see the very first line (such as the column headers of a CSV file), you can modify the output using the -n (number) flag.
To print only the first 3 lines of a file, run:
head -n 3 /var/log/syslog
To print the first 50 lines, run:
head -n 50 /var/log/syslog
How to View Multiple Files Simultaneously
The head command becomes exceptionally powerful when you need to quickly compare the beginnings of several different files at once.
You can pass multiple filenames to the command separated by a space:
head -n 5 error.log access.log
When you do this, the terminal output will be neatly formatted. It will print a small header containing the name of the first file (e.g., ==> error.log <==), print the first 5 lines, leave a blank space, print the header for the second file, and then print its first 5 lines. This makes comparing log files or configuration backups remarkably fast.