tail - Linux


Overview

The tail command in Linux outputs the last part, typically referred to as the “tail”, of files. It is most commonly used to view the end of text files or logs in real-time. tail can be especially handy for monitoring logs that append data frequently, such as server logs, during system operations or debugging.

Syntax

The basic syntax of the tail command is:

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

This command reads one or more files and outputs the last part of their contents. If no file is specified, tail reads from standard input.

Options/Flags

  • -f, --follow: Continuously prints new content appended to the file; commonly used for viewing changing logs.
  • -n, --lines=[-]NUM: Specifies the number of lines to show from the file’s end (default is 10). Use -n +NUM to output lines starting from NUM.
  • --pid=PID: Useful with -f, this option ends the tail when the process with the specified PID terminates.
  • -c, --bytes=[-]NUM: Similar to -n, but specifies the number of bytes.
  • -q, --quiet, --silent: Suppresses printing of headers when multiple files are being monitored.
  • -v, --verbose: Always output headers with file names when tracking multiple files.
  • --retry: Keeps trying to open a file even if it is inaccessible at the start or momentarily unavailable.

Examples

  1. View the last 10 lines of a file:
    tail /var/log/syslog
    
  2. Follow a log file in real-time:
    tail -f /var/log/apache2/access.log
    
  3. View the last 20 lines from multiple files:
    tail -n 20 file1.txt file2.txt
    
  4. Show only new lines added from the 5th line to the end since opening the file:
    tail -n +5 -f filename.log
    

Common Issues

  • File inaccessible at runtime: Files can occasionally be locked or become unavailable. To handle such cases, use the --retry option.
  • Large volume output: Delay in viewing updates due to buffering when using -f with a large file. Optimize viewing by combining with other commands like grep.

Integration

tail is often piped with other commands to enhance monitoring or file management tasks:

  • Monitor specific patterns in logs:
    tail -f /var/log/syslog | grep "error"
    
  • Extract updates and handle through a script:
    tail -f logfile | while read line; do
      echo "New log entry: $line"
    done
    
  • head: View the starting part of files, opposite of tail.
  • cat: Concatenate and display files, useful for viewing entire files.
  • grep: Search for patterns within input text, frequently used with tail for filtering output.

For more advanced usage and detailed information, refer to the GNU coreutils online documentation for tail: GNU Coreutils – tail