Archives and disk tools

Linux commands: tail

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, and that’s usually what you’re after.

You can choose how many lines with -n:

tail -n 10 <filename>

Change the number to see more or fewer lines. Here is a quick way to see it in action, with a file you build on the spot:

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

You can also print the whole file starting from a specific line, by putting + before the 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. On numbers.txt, tail -n +98 prints the same three lines as tail -n 3, and that’s only because the file has exactly 100 lines.

The best use of tail, in my opinion, is the -f option. It opens the file at the end and keeps watching it. Any time new content is appended, it’s printed in your terminal right away. This is great for watching log files:

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 "

I keep one of these open in a terminal tab whenever I deploy something. If the errors start scrolling, I know before anyone emails me.

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.

If you get the filename wrong, tail says so and exits:

tail -f missing.log
tail: cannot open 'missing.log' for reading: No such file or directory

Check the path with ls. On a server, also check permissions: many log files under /var/log are readable only by root, so you may need sudo tail -f.

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

Lesson completed