Working with long log files and only interested in the last few lines? Or want to quickly peek at the beginning of a configuration file without opening it in an editor? For that, Linux offers two simple but very useful commands: head and tail.
What is head
The head command prints the beginning of a file — by default the first 10 lines. It is useful when you want to quickly check what is in a file without opening its entire contents.
head /var/log/syslog head -n 20 /var/log/syslog
The first command prints the first 10 lines, the second the first 20. The -n parameter (or just -) tells it how many lines we are interested in.
What is tail
The tail command is the opposite of head — it prints the end of a file, by default the last 10 lines. This is especially useful with logs, where the newest entries are at the end of the file.
tail /var/log/syslog tail -n 50 /var/log/syslog
tail -f: Following in Real Time
The most powerful feature of tail is the ability to watch a file live. With the -f parameter (follow), tail first prints the last 10 lines already in the file and then stays open. When a new entry appears in the file, it immediately prints it to the screen instead of waiting for the next one.
tail -f /var/log/syslog
You stop the command with Ctrl+C. This is an indispensable tool for troubleshooting on a server, as you instantly see every new entry in the log.
Practical Examples
| Command | What it does |
|---|---|
| head index.html | Prints the first 10 lines of the file |
| head -n 5 index.html | Prints the first 5 lines |
| tail syslog | Prints the last 10 lines |
| tail -n 100 syslog | Prints the last 100 lines |
| tail -f syslog | Follows the file in real time |
| head -c 1024 image.jpg | Prints the first 1024 bytes |
Pipe Combinations
The real power of head and tail shows when combined with other commands through pipes (the | symbol). A pipe passes the output of one command to the input of another, and from the result you take only the part you are interested in.
ls -la | head -5 ps aux | tail -n 20 cat access.log | grep "error" | tail -n 10
The first command prints only the first 5 lines of the file listing, the second the last 20 processes, and the third the last 10 lines containing the word "error". Such chains of commands are an everyday tool for every system administrator.
The head and tail commands are small, fast, and present on every Linux installation. When you work on a server over SSH and need a quick look at a log, these two commands save you a lot of time — without opening large files in an editor.