Difference Between Head and Tail Commands in Linux
In the Linux operating system, head and
tail are fundamental command-line utilities used for
viewing parts of text files or piped data streams. While both commands
are designed to inspect file contents without loading entire documents
into memory, their fundamental difference lies in where they read:
head outputs the beginning of a file, whereas
tail outputs the end. This article explains the technical
differences, syntax, common options, and best use cases for both
commands.
The Core Difference
headprints the first part of a file. By default, runninghead filename.txtdisplays the first 10 lines of the specified file.tailprints the final part of a file. By default, runningtail filename.txtdisplays the last 10 lines of the specified file.
Key Features and Common Options
Both commands share similar syntax and common flags, but each has unique capabilities tailored to its purpose.
Specifying Line Count
(-n)
You can override the default 10-line limit on either command using
the -n option:
head -n 5 filename.txtoutputs the first 5 lines.tail -n 20 filename.txtoutputs the last 20 lines.
Specifying Byte Count
(-c)
Both utilities can read files by data size rather than lines using
the -c flag:
head -c 100 filename.txtoutputs the first 100 bytes of the file.tail -c 50 filename.txtoutputs the last 50 bytes of the file.
Real-Time File Monitoring
(tail -f)
The most significant operational difference is tail's
ability to follow files in real time. The -f (follow)
option keeps the file open and prints new lines as they are appended to
the file:
tail -f /var/log/syslogmonitors system logs continuously as events occur.
The head command does not possess a follow option
because beginning lines in a file do not change dynamically during
normal logging operations.
When to Use Each Command
Use
headwhen:- Checking configuration file headers to identify file formats or metadata.
- Previewing the columns of a large CSV or tabular dataset.
- Confirming that a script or program began executing and generated initial output.
Use
tailwhen:- Monitoring system, server, or application logs for recent errors and warnings.
- Troubleshooting live services in real time using the
-fflag. - Verifying the most recently added records in an audit trail or data log.