Linux commands: tail

By

Learn how the Linux tail command shows the end of a file, prints the last lines with -n, and follows a log live as it grows with the tail -f option.

~~~

tail prints the final part of a file. Called with just a filename, it shows the last 10 lines. That alone is useful — the end of a log file is where the newest information lives.

But the best use case of tail in my opinion is when called with the -f option. It opens the file at the end, and watches for file changes. Any time there is new content in the file, it is printed in the window. This is great for watching log files, for example:

tail -f /var/log/system.log

To exit, press ctrl-C.

While it runs, you can pipe it into other tools. This watches a web server log and shows only the server errors, as they happen:

tail -f /var/log/nginx/access.log | grep " 500 "

One thing to know about -f: it keeps following the file it originally opened. Log rotation replaces that file with a fresh empty one, and your tail -f goes silent, still attached to the old deleted file. When that’s a risk, use -F instead: it notices the swap and reopens the file by name.

You can print the last 10 lines in a file:

tail -n 10 <filename>

Change the number to see more or fewer lines. Here is a quick way to verify the behavior with a file you build on the spot:

seq 1 100 > numbers.txt
tail -n 3 numbers.txt
# 98
# 99
# 100

You can print the whole file content starting from a specific line using + before the line number:

tail -n +10 <filename>

Watch the meaning flip: -n 10 means “the last 10 lines”, while -n +10 means “everything from line 10 to the end”. Mixing the two up is a classic source of confusion.

The natural companion is head, which prints the beginning of a file instead of the end.

tail can do much more and as always my advice is to check man tail.

This command works on Linux, macOS, WSL, and anywhere you have a UNIX environment

Tagged: CLI · All topics
~~~

Related posts about cli: