tail
Overview
The tail
command displays the last lines of files or input streams. It’s essential for monitoring log files and examining file endings.
Syntax
tail [options] [file...]
Common Options
Option | Description |
---|---|
-n num |
Show last num lines |
-c num |
Show last num bytes |
-f |
Follow file changes |
-F |
Follow with retry |
-q |
Suppress headers |
-v |
Always show headers |
-s num |
Sleep seconds between checks |
--pid=pid |
Terminate after process dies |
--retry |
Keep trying to open file |
Key Use Cases
- Monitor log files
- View file endings
- Real-time file watching
- Debug running processes
- System monitoring
Examples with Explanations
Example 1: Default Usage
tail file.txt
Shows last 10 lines of file
Example 2: Follow Log File
tail -f /var/log/syslog
Continuously monitors log file for new entries
Example 3: Specific Line Count
tail -n 20 error.log
Shows last 20 lines
Example 4: Multiple Files
tail -f /var/log/*.log
Follows multiple log files simultaneously
Follow Mode Options
Option | Behavior |
---|---|
-f |
Follow by file descriptor |
-F |
Follow by name (handles rotation) |
--retry |
Keep trying if file doesn’t exist |
--pid=pid |
Stop when process dies |
Common Usage Patterns
Monitor application logs:
tail -f /var/log/apache2/error.log
Watch system logs:
tail -f /var/log/messages
Debug scripts:
tail -f script.log & ./script.sh
Advanced Usage
Follow with retry:
tail -F /var/log/app.log
Stop after process ends:
tail -f --pid=$PID logfile.log
Custom sleep interval:
tail -f -s 0.1 fast_changing.log
Performance Analysis
- Efficient for file monitoring
- Low CPU usage in follow mode
- Handles log rotation well with -F
- Good for real-time monitoring
- Minimal memory footprint
Best Practices
- Use -F for log files that rotate
- Combine with grep for filtering
- Use –pid for temporary monitoring
- Consider multitail for multiple files
- Be aware of file descriptor limits
Integration Examples
Filtered monitoring:
tail -f /var/log/syslog | grep ERROR
Multiple log analysis:
tail -f /var/log/{messages,secure,maillog}
Application debugging:
tail -f app.log | while read line; do echo "$(date): $line" done
Log Rotation Handling
Follow by name (handles rotation):
tail -F /var/log/app.log
Retry if file disappears:
tail -f --retry /var/log/app.log
Scripting Applications
Wait for log entry:
tail -f app.log | grep -q "Server started" && echo "Ready"
Monitor until condition:
timeout 60 tail -f deploy.log | grep -q "Deployment complete"
System Monitoring
Watch system load:
tail -f /proc/loadavg
Monitor memory:
watch -n 1 'tail -5 /proc/meminfo'