stat - Linux


Overview

The stat command in Linux is used to display detailed information about given files or file systems. Its primary purpose is to show file attributes like size, inode information, access, modify, and change times. It’s particularly useful for system administrators and developers who need detailed information about files and directories for troubleshooting, scripting, or system maintenance.

Syntax

The basic syntax of the stat command is:

stat [OPTION]... [FILE]...
  • [OPTION] refers to the various flags and parameters that can be used to modify the output of the command.
  • [FILE] is one or more files or directories to get statistics for.

Options/Flags

Here are some commonly used options for the stat command:

  • -L : Follow symbolic links, to show stats on the file they point to rather than the symlink itself.
  • -f : Display filesystem status instead of file status if a file name is provided.
  • -c –format=FORMAT : Specify the output format. This uses placeholders (like %a for access rights, %s for size) to tailor the output.
  • -t : Use terse output format, which reduces the output to only the essential information, useful for parsing in scripts.
  • --format=FORMAT : Same as -c, defines a custom format.

Examples

  1. Basic Usage:
    Display statistics for a file called example.txt:

    stat example.txt
    
  2. Custom Format:
    Show only the size and last modification date of a file:

    stat -c "%s %y" example.txt
    
  3. Check File System Status:
    Use stat to get information about the filesystem of a particular directory:

    stat -f /home
    

Common Issues

  • Permission Denied: Users may encounter this error if they do not have the necessary permissions to view a file. To resolve, check the file permissions or run with elevated privileges (e.g., using sudo).

  • File Not Found: Ensure the correct file path is used. Check for typos and verify that the file exists in the specified directory.

Integration

Combine stat with other commands for more comprehensive scripts or data processing:

  • Find and Stat:
    Use find to search for files and stat to display details about them. For example, find all JPEG files and get detailed stats:

    find . -name "*.jpg" -exec stat {} \;
    
  • Awk with Stat:
    Extract specific information using awk, for example, list files in a directory and their sizes:

    stat --format="%n %s" * | awk '{print "File:" $1 " Size:" $2 " bytes"}'
    
  • ls – List directory contents, can show file sizes and permissions.
  • df – Report file system disk space usage.
  • du – Estimate file space usage.

For further reading, you can refer to the official GNU Coreutils documentation for stat. This resource provides a comprehensive understanding of the command and its intricacies.