Website Vidya
Linux & ServersStep-by-Step Guide

tail Command in Linux: Output End of Files and Follow Live Logs

Learn tail command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

RR
Rajesh RayLead Systems Educator
Published:
9 min read
PDF Cheat Sheet
tail Command in Linux: Output End of Files and Follow Live Logs
AI Executive SummaryWebsiteVidya AI

9 min read

Learn tail command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What tail Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

The tail command in linux is an indispensable tool in every sysadmin's diagnostic toolkit. As the complementary counterpart to the head utility, tail outputs the tail end of text files or piped input streams. Its default behavior is to output the last 10 lines of the target, but its capabilities extend far beyond static inspection.

In modern operations and DevOps workflows, tail is most famous for its follow flags: -f and -F. These options allow engineers to monitor application and system logs in real time as events occur, tracking errors, transaction volumes, and service initialization steps directly from the terminal prompt.

Understanding how tail interfaces with the Linux kernel's inotify subsystem, how it handles log file rotation, and how to monitor multiple log files simultaneously allows you to maintain real-time observability over production servers with minimal system overhead.

Advertisement
tail Command in Linux: Output End of Files and Follow Live Logs — syntax, flags, and practical terminal workflow diagram
tail Command in Linux: Output End of Files and Follow Live Logs — command syntax, key options, and production workflow reference.

What tail Does and When to Use It

Under the hood, GNU coreutils tail optimizes file reading using two distinct mechanisms depending on the requested flags. When invoked on a static regular file with -n N, tail avoids reading the entire file from the beginning. Instead, it uses lseek(2) to jump near the end of the file based on average line length heuristics, reading backward in chunks until it counts the requested number of newline characters (\n). Once found, it streams forward to EOF.

When invoked with live follow mode (-f or -F) on modern Linux systems, tail leverages the kernel's inotify(7) API rather than sleep polling. It registers an inotify watch on the target file descriptor or its parent directory. When a daemon writes data, the kernel triggers an IN_MODIFY event, waking tail from sleep to immediately read(2) the appended bytes and write(2) them to stdout. When invoked with -F (--retry --follow=name), tail additionally watches for IN_MOVE_SELF and IN_CREATE events, seamlessly reopening log files when logrotate moves or recreates them.

Under the hood, tail gathers runtime telemetry or dispatches control signals by reading virtual filesystems mounted at /proc and /sys, or by communicating with PID 1 (systemd) over D-Bus. Using flags such as -n NUM, -f, -F, -c NUM turns raw process and service tables into actionable diagnostics during incident response.

Availability and Installation Across Linux Distributions

The tail utility is packaged in coreutils across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:

Advertisement

Before running administrative tasks or automation scripts, verify whether tail is installed and inspect which binary path and version your shell resolves:

type -a tail
tail --version 2>/dev/null || man -f tail

# Illustrative output (reviewed against documentation)
tail is /usr/bin/tail
tail (coreutils)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y coreutils

# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y coreutils

# Arch Linux
sudo pacman -S --noconfirm coreutils

# Alpine Linux
sudo apk add --no-cache coreutils

Command Syntax, Arguments, and Exit Status Codes

tail [OPTION]... [FILE]...

The standard invocation syntax is tail [OPTION]... [FILE].... If no FILE operands are specified, or when a hyphen (-) is given, tail reads from standard input (stdin).

The -n option specifies the number of lines to output (e.g. -n 25). If prefixed with a plus sign (e.g. -n +20), tail reverses its logic, outputting lines starting from line 20 all the way to the end of the file. The -c option allows specifying raw byte counts rather than lines.

  • 0 — Successful completion; all specified line ranges emitted without error.
  • 1 — Operational error; file unreadable, permission denied, or invalid flag arguments.
  • 2 — Command-line syntax error.

Important Options and Flags Reference

Option / FlagLong Form / ArgumentTechnical Behavior and Purpose
-n NUM--lines=NUMOutput the last NUM lines (default 10); use +NUM to output starting at line NUM.
-f--follow[={name|descriptor}]Output appended data as the file grows; defaults to descriptor.
-F-FSame as --follow=name --retry; tracks file across log rotation and renames.
-c NUM--bytes=NUMOutput the last NUM bytes; use +NUM to output starting with byte NUM.
-q--quiet, --silentNever output headers giving file names when viewing multiple files.
-v--verboseAlways output headers giving file names.
--pid=PID--pid=PIDWith -f, terminate tail automatically when process PID dies.
-s SEC--sleep-interval=SECWith -f, sleep for SEC seconds between polling iterations (fallback mode).

The distinction between -f and -F is one of the most critical operational details in Linux log monitoring. The standard -f (--follow=descriptor) keeps the initial open file descriptor. When logrotate moves /var/log/app.log to app.log.1 and creates a new app.log, tail -f remains attached to the renamed historical file and stops reporting new events.

Advertisement

In contrast, -F (--follow=name --retry) tracks the filename itself. When logrotate rotates and truncates the file, tail -F automatically reopens the newly created file with the same name, continuing uninterrupted real-time streaming.

When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.

Practical Basic and Advanced Usage Examples

1. Display the Last 20 Lines of a System Log

View the most recent entries in the kernel ring log buffer.

tail -n 20 /var/log/kern.log | head -n 3

# Illustrative output (reviewed against documentation)
Oct 22 14:02:11 host kernel: [   12.842100] eth0: Link is Up - 1000Mbps/Full
Oct 22 14:02:11 host kernel: [   12.842145] IPv6: ADDRCONF(NETDEV_CHANGE): eth0: link becomes ready
Oct 22 14:05:30 host kernel: [  211.940120] usb 1-1: new high-speed USB device number 2

The -n 20 flag instructs tail to output exactly the last 20 lines of the file.

2. Stream Real-Time Updates with Follow Mode (-f)

Monitor active incoming HTTP requests as they hit an Nginx web server.

tail -f /var/log/nginx/access.log

# Illustrative output (reviewed against documentation)
198.51.100.12 - - [22/Oct/2026:16:40:01 +0000] "GET /api/v1/health HTTP/1.1" 200 12
192.0.2.89 - - [22/Oct/2026:16:40:03 +0000] "POST /checkout HTTP/1.1" 200 452
# Continuously updates as new requests arrive...

tail keeps the file open and immediately outputs any new lines appended by Nginx.

3. Follow Across Log Rotation Using -F

Monitor an active application log while ensuring tracking continues through midnight log rotation.

tail -F /var/log/application.log

# Illustrative output (reviewed against documentation)
tail: '/var/log/application.log' has been replaced;  following new file
2026-10-23 00:00:01 INFO Day rollover complete. Log initialized.

The -F option detects when logrotate renames the old file and re-attaches to the newly created replacement.

4. Output Starting from a Specific Line Number (+NUM)

Skip a 2-line header in a CSV export and print everything from line 3 onward.

cat << 'EOF' > data.csv
Report Generated: 2026-10-22
ID,Name,Status
101,Node1,Active
102,Node2,Inactive
EOF
tail -n +3 data.csv

# Illustrative output (reviewed against documentation)
101,Node1,Active
102,Node2,Inactive

Using the plus sign (+3) instructs tail to emit all lines from line 3 to the end of the file.

5. Monitor Multiple Log Files Simultaneously

Follow both Nginx access and error logs in a single terminal session.

tail -f /var/log/nginx/access.log /var/log/nginx/error.log

# Illustrative output (reviewed against documentation)
==> /var/log/nginx/access.log <==
198.51.100.12 - - [22/Oct/2026:16:42:01 +0000] "GET / HTTP/1.1" 200 1204

==> /var/log/nginx/error.log <==
2026/10/22 16:42:05 [warn] 1104#1104: *120 a client request body is buffered to a temporary file

tail automatically prefixes each stream with a header banner indicating which file generated the log entry.

6. Terminate Tail Automatically When Process Exits (--pid)

Monitor a background job's log file and automatically terminate the tail command when the worker exits.

python3 /opt/scripts/long_task.py > /tmp/task.log 2>&1 &
TASK_PID=$!
tail -f --pid="$TASK_PID" /tmp/task.log

# Illustrative output (reviewed against documentation)
[Step 1/3] Processing records...
[Step 2/3] Generating summary reports...
[Step 3/3] Task completed successfully.
# tail exits automatically when TASK_PID terminates

The --pid flag monitors the worker process ID; once the process exits, tail closes the file and returns to prompt.

Real-World Workflows, Pipelines, and Shell Automation

Live Production Alert Monitor: Real-Time Error Pipeline

Stream live logs, filter for critical anomalies, and trigger terminal alert notifications.

#!/usr/bin/env bash
set -euo pipefail

LOG="/var/log/nginx/error.log"
echo "Monitoring $LOG for critical alerts (press Ctrl+C to exit)..."

tail -F -n 0 "$LOG" | while read -r line; do
  if echo "$line" | grep -qE '[crit]|[alert]|[emerg]'; then
    printf "\033[1;31m[CRITICAL ALERT]\033[0m %s\n" "$line"
  fi
done

# Illustrative output (reviewed against documentation)
Monitoring /var/log/nginx/error.log for critical alerts (press Ctrl+C to exit)...
[CRITICAL ALERT] 2026/10/22 16:45:10 [crit] 1104#1104: *882 connect() to upstream failed

Using tail -F -n 0 starts following only new entries appended from the current moment forward, piping directly into a bash alerting loop.

Log Rotation Validation: Testing logrotate Hooks

Verify that application log rotation works correctly without dropping live stream consumers.

#!/usr/bin/env bash
set -euo pipefail

TEST_LOG="/tmp/rotate_test.log"
echo "Initializing test log: $TEST_LOG"
echo "Initial entry" > "$TEST_LOG"

# Start tail in background tracking filename
tail -F "$TEST_LOG" > /tmp/tail_captured.log 2>&1 &
TAIL_PID=$!

sleep 1
echo "Simulating logrotate: moving file and recreating..."
mv "$TEST_LOG" "$TEST_LOG.1"
echo "Rotated entry" > "$TEST_LOG"
sleep 1

kill "$TAIL_PID" || true
cat /tmp/tail_captured.log

# Illustrative output (reviewed against documentation)
Initial entry
tail: '/tmp/rotate_test.log' has been replaced;  following new file
Rotated entry

This workflow tests logrotate resilience, proving that tail -F detects file replacement and resumes capture seamlessly.

Pipelines, Redirection, Quoting, and Shell Expansion

When embedding tail inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.

Permissions, Security Implications, and Safe Execution

Viewing system logs in /var/log (such as /var/log/auth.log or /var/log/secure) requires root or adm group membership. Avoid changing file permissions on /var/log to 777 to allow unprivileged tail access; instead, add trusted users to the adm or systemd-journal group.

When using tail in automated scripts that parse untrusted logs, ensure the downstream parser handles malicious payload injection (such as terminal escape sequences that attempt to manipulate terminal titles or trigger exploits).

GNU/Linux, BSD, and BusyBox Implementation Differences

GNU coreutils tail implements inotify-based file tracking, providing instant updates with zero CPU utilization while waiting for new data. On BSD systems (FreeBSD, macOS), tail historically relies on kqueue(2) or polling.

On Alpine Linux, default BusyBox tail supports standard -n, -f, and -c flags, but does NOT support -F (following across log rotation) or --pid. In Alpine Docker containers where log rotation must be monitored, install GNU coreutils: apk add --no-cache coreutils.

Troubleshooting Common Errors and Diagnostics

tail -f stops updating after logrotate runs

Root Cause: tail was invoked with -f, which follows the file descriptor. When logrotate renames the file, tail remains attached to the renamed historical file.

Resolution: Use tail -F instead of tail -f to follow by filename across rotations.

tail -F /var/log/application.log

tail: cannot open '/var/log/auth.log' for reading: Permission denied

Root Cause: The file is owned by root:adm with 0640 permissions, and the current user lacks administrative privileges.

Resolution: Run tail with sudo or add your user account to the adm group.

sudo tail -n 50 /var/log/auth.log

tail: unrecognized option '--pid'

Root Cause: The system is running BusyBox tail (common in minimal Alpine Docker images) which lacks GNU extensions.

Resolution: Install GNU coreutils in the container or manage process lifecycles via standard shell kill commands.

apk add --no-cache coreutils

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
tail -f tracks the underlying file descriptor. If the file is renamed or rotated (e.g. by logrotate), it continues following the old file. tail -F tracks the filename, automatically re-attaching when the file is replaced or recreated.
Press Ctrl+C to send a SIGINT signal to the tail process, returning control back to your terminal shell.
Combine -n and -f: tail -n 100 -f /var/log/syslog will first print the last 100 lines and then keep streaming new entries.
Yes. Pass -n 0 with follow mode: tail -n 0 -f /var/log/nginx/access.log will print nothing initially and only output lines written after the command was launched.
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout