Linux tail command
The tail
command in Linux is used to display the last part (or "tail") of a file. By default, it shows the last 10 lines of a file, but you can customize the output by using various options. It is especially useful for monitoring log files in real-time or viewing the most recent content of large files.
Basic Syntax:
options
: Various flags to modify the behavior of the command.file(s)
: One or more files to be displayed.
Common Use Cases for tail
:
Display the Last 10 Lines of a File:
- By default,
tail
shows the last 10 lines of a file.
- Output (example):
- By default,
Display the Last N Lines of a File:
- Use the
-n
option to specify the number of lines to display. For example, to show the last 20 lines:
- Output:
- Use the
Follow the File in Real-Time:
- The
-f
option allows you to "follow" a file in real-time. This is useful for monitoring log files as they are updated.
- Output (real-time):
- The
Follow Multiple Files:
- You can follow multiple files at once by specifying multiple file names:
- Output:
Display the Last Lines of Multiple Files:
- You can also use
tail
to display the last N lines from multiple files. Use the-n
option followed by the file names:
- You can also use
Show Last Few Bytes of a File:
- The
-c
option allows you to specify the number of bytes instead of lines.
- This will show the last 100 bytes of the file.
- The
Exit after a Specific Number of Lines:
- You can use the
-n
option in combination with the-f
option to limit the number of linestail
should display before exiting.
- This will display the last 50 lines of the file and continue to follow new lines as they are written to the file.
- You can use the
Key Options:
-n <num>
: Display the last<num>
lines. E.g.,tail -n 20 file.log
.-f
: Follow the file as it grows in real-time.-c <num>
: Show the last<num>
bytes instead of lines.-q
: Suppress headers when following multiple files.-v
: Print file headers with each file when following multiple files.
Example Use Case: Real-time Log Monitoring
To monitor a system log file like /var/log/syslog
in real-time and watch for new entries:
If an error or issue occurs, you will see it in real-time, making it useful for troubleshooting.
Conclusion
The tail
command is a powerful and versatile tool for viewing the end of a file in Linux. Whether you need to check the latest system logs, follow logs as they update, or simply view the last few lines of a file, tail
is an essential tool for administrators and developers.