0
0
Linux-cliHow-ToBeginner · 3 min read

How to Use Tail Command in Linux: Syntax and Examples

The tail command in Linux shows the last part of a file, usually the last 10 lines by default. You can use options like -n to specify the number of lines or -f to follow a file as it grows in real time.
📐

Syntax

The basic syntax of the tail command is:

  • tail [options] [file]

Where:

  • options modify the behavior, like how many lines to show or to follow the file.
  • file is the name of the file you want to read the end of.
bash
tail [options] [file]
💻

Example

This example shows how to display the last 5 lines of a file named logfile.txt and then follow the file to see new lines as they are added.

bash
tail -n 5 logfile.txt

# To follow the file in real time
 tail -f logfile.txt
Output
Line 96: Error detected Line 97: Restarting service Line 98: Service started Line 99: Connection established Line 100: Listening on port 8080 # (When running tail -f, new lines will appear here as they are added)
⚠️

Common Pitfalls

Some common mistakes when using tail include:

  • Forgetting to specify the number of lines with -n and expecting a different default.
  • Using tail -f without knowing how to stop it (use Ctrl+C to exit).
  • Trying to tail a file that does not exist, which will cause an error.
bash
tail -n logfile.txt  # Wrong: missing number after -n

# Correct usage:
tail -n 10 logfile.txt
Output
tail: option requires an argument -- 'n' Try 'tail --help' for more information.
📊

Quick Reference

OptionDescription
-n Show the last lines of the file
-fFollow the file as it grows, showing new lines in real time
-c Show the last bytes of the file
--helpDisplay help information about tail command

Key Takeaways

Use tail -n to specify how many lines to display from the end of a file.
Use tail -f to watch a file update live, useful for logs.
Always check the file exists before using tail to avoid errors.
Stop a running tail -f with Ctrl+C.
The default output of tail is the last 10 lines if no options are given.