tail -f


tail -f (follow content as it grows)

The tail -f command is a critical tool for system administrators and developers. The -f (follow) option transforms tail from a one-time command into a live monitoring tool, continuously displaying new lines as they are added to a file.


Example 1: Live monitoring of a log file

# Watch the system security log in real-time for new entries
tail -f /var/log/secure

Explanation: This command displays the last few lines of the security log and then waits. As new login attempts or security events are logged, they will appear on your screen instantly. Press Ctrl-C to exit.


Example 2: Following a file with a specified number of lines

# Display the last 100 lines and then follow the file for new changes
tail -n 100 -f /var/log/httpd/access_log

Explanation: You can combine -n and -f. This command will first display the last 100 lines of the web server's access log and then begin to follow it for new requests.


Example 3: Following multiple files at once

# Monitor both the web server access and error logs simultaneously
tail -f /var/log/httpd/access_log /var/log/httpd/error_log

Explanation: tail -f can monitor several files at the same time. It will print a header to show which file is receiving new content, making it easy to watch related logs together.


Example 4: Following a file that may be rotated or renamed

# Follow a log file by its name, automatically reopening it if it's rotated
tail -F /var/log/maillog

Explanation: The capital -F option is more robust for log files. It combines the follow behavior with a retry mechanism, so if the log file is renamed (a common action during log rotation), tail will detect it and open the new file.


Example 5: Following and filtering with grep

# Watch an application log in real-time, but only show lines that contain "ERROR"
tail -f application.log | grep "ERROR"

Explanation: This powerful combination lets you create a live, filtered view of a log. tail -f continuously feeds the log into grep, which only prints the lines that match your specified pattern.


Example 6: Following with a specific process ID

# Follow a log file until a specific process (e.g., PID 12345) terminates
tail -f my.log --pid=12345

Explanation: The --pid option tells tail to automatically exit once the specified process ID is no longer running. This is extremely useful in scripts for monitoring a temporary process and its log output.


Example 7: Controlling the sleep interval

# Follow a file on a busy system, checking for changes every 5 seconds
tail -f -s 5 /var/log/very_busy_log

Explanation: The -s option allows you to specify the sleep interval in seconds. Increasing it from the default of 1 second can reduce the system load when monitoring very active files on a resource-constrained machine.