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:
optionsmodify the behavior, like how many lines to show or to follow the file.fileis 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.txtOutput
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
-nand expecting a different default. - Using
tail -fwithout knowing how to stop it (useCtrl+Cto 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.txtOutput
tail: option requires an argument -- 'n'
Try 'tail --help' for more information.
Quick Reference
| Option | Description |
|---|---|
| -n | Show the last |
| -f | Follow the file as it grows, showing new lines in real time |
| -c | Show the last |
| --help | Display 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.