Skip to content

tail Command: Monitoring File Changes in Real-Time

Summary

The tail command is a powerful utility for displaying the last part of a file. It's particularly useful for monitoring log files or other files that are being actively written to, allowing you to see changes in real-time.

Introduction

The tail command is a standard Unix utility that outputs the last part of files. By default, it displays the last 10 lines of a specified file. However, its real power lies in its ability to "follow" a file, continuously displaying new lines as they are added, making it an essential tool for system administrators and developers alike.

Use Case and Examples

Displaying the last 10 lines of a file

tail myfile.txt
This command will display the last 10 lines of the file named myfile.txt.

Displaying the last 20 lines of a file

tail -n 20 myfile.txt
This command will display the last 20 lines of myfile.txt. The -n flag specifies the number of lines to display.

Following a file for real-time updates

tail -f /var/log/syslog
This command will continuously display new lines added to the /var/log/syslog file. Press Ctrl+C to stop following the file.

Following multiple files simultaneously

tail -f file1.txt file2.txt
This command will monitor both file1.txt and file2.txt for changes, prefixing each line with the file name.

Displaying lines starting from a specific line number

tail -n +50 myfile.txt
This command will display all lines of myfile.txt starting from line 50. The + sign indicates that the output should begin from that line number instead of displaying a count from the end.

Commonly used flags

Flag Description Example
-n, --lines=K Outputs the last K lines, instead of the last 10; or use -n +K to output lines starting with the Kth. tail -n 50 myfile.txt (displays the last 50 lines) tail -n +20 myfile.txt (displays the file starting from line 20)
-f, --follow[={name|descriptor}] Output appended data as the file grows. name means follow by file name, which is the default; descriptor means follow by file descriptor. tail -f /var/log/apache2/access.log (monitors the Apache access log for new entries)
-s, --sleep-interval=S With -f, sleep for approximately S seconds (default 1.0) between iterations. tail -f -s 5 /var/log/mylog.log (checks the log file for new entries every 5 seconds)
--pid=PID With -f, terminate after process ID, PID dies. tail -f --pid=1234 /var/log/process.log (stops following the log when process with PID 1234 terminates)
-q, --quiet, --silent Never output headers giving file names. tail -q file1.txt file2.txt (displays the contents of the files without headers)
-v, --verbose Always output headers giving file names. tail -v file1.txt (forces headers to be displayed, even when only one file is specified)


Share on Share on

Comments