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.
9 min read
Learn tail command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
- What tail Does and When to Use It
- Availability and Installation Across Linux Distributions
- Command Syntax, Arguments, and Exit Status Codes
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.
The tail command in Linux prints the last 10 lines of files or standard input by default, and can continuously stream new data appended to files in real time. Run tail -n 50 /var/log/syslog to view the last 50 lines, or tail -f /var/log/nginx/access.log (or -F to handle log rotation) to stream live log events.
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.
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:
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 / Flag | Long Form / Argument | Technical Behavior and Purpose |
|---|---|---|
-n NUM | --lines=NUM | Output 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 | -F | Same as --follow=name --retry; tracks file across log rotation and renames. |
-c NUM | --bytes=NUM | Output the last NUM bytes; use +NUM to output starting with byte NUM. |
-q | --quiet, --silent | Never output headers giving file names when viewing multiple files. |
-v | --verbose | Always output headers giving file names. |
--pid=PID | --pid=PID | With -f, terminate tail automatically when process PID dies. |
-s SEC | --sleep-interval=SEC | With -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.
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
tail is a read-only utility. However, running tail -f /var/log/app.log > /var/log/app.log will immediately truncate the log file to 0 bytes due to shell redirection, resulting in permanent data loss.
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
Alternatives, Related Commands, and Related Tutorials
- Grep Command in Linux: Search Text, Files, and Directories — Practical syntax, flags, and examples for
grep. - tee Command in Linux: Split and Redirect Streams with Examples — Practical syntax, flags, and examples for
tee. - less Command in Linux: View, Navigate, and Search Text Files — Practical syntax, flags, and examples for
less. - sort Command in Linux: Sort Lines of Text and Numerical Data — Practical syntax, flags, and examples for
sort. - 25 Best Linux Commands Every Sysadmin Should Know — Core command-line utilities for daily Linux server administration.
- How to Find a File in Linux from the Command Line — Practical file search patterns across Linux directories.
- Linux Commands Knowledge Hub (#linux-commands) — Browse all Linux command-line tutorials and system administration references.
Authoritative References and Official Documentation

The Linux Command Line, 2nd Edition: A Complete Introduction
Frequently Asked Questions
Quick answers to common questions and configurations
/var/log/syslog will first print the last 100 lines and then keep streaming new entries./var/log/nginx/access.log will print nothing initially and only output lines written after the command was launched.Editorial Disclosure: Website Vidya is supported by our readers. When you purchase hosting, tools, or software through our verified partner links, we may earn an affiliate commission at no extra cost to you. We only recommend solutions we trust and rigorously verify.
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.
Most Read Guides
TrendingUbuntu Server Not Booting? 10 Simple Steps to Fix It Fast
How to Create a 3D Button in HTML and CSS: Easy Steps
How to Install Python and Pip on Ubuntu 24.04 LTS
How to Install Nginx on Ubuntu 24.04
How to Install Python on Ubuntu 24.04 LTS
Related Technical Guides
Tested runbooks, server administration walkthroughs, and troubleshooting guides

Join the Conversation & Perspective
Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.
No comments on this guide yet. Be the first to share your thoughts or ask a question!