CommandsLinux

Stat Command on Linux with Examples

Use Stat Command on Linux

Delving into the Linux filesystem requires powerful tools that provide detailed insights about files and directories. The stat command stands out as one of the most useful utilities for system administrators and Linux enthusiasts alike. This versatile tool reveals crucial metadata about files that remains hidden with standard commands like ls. Whether you’re troubleshooting permission issues, conducting security audits, or simply exploring your system’s organization, mastering the stat command will significantly enhance your Linux proficiency.

What is the Stat Command in Linux?

The stat command is a powerful utility included in the GNU coreutils package that displays comprehensive metadata about files and filesystems. Unlike simpler commands that provide basic information, stat offers an extensive view of a file’s attributes, permissions, timestamps, and storage details.

This command functions as a one-stop-shop for viewing critical file information such as:

  • File size and disk allocation
  • Access permissions in both octal and symbolic notation
  • User and group ownership identifiers
  • Timestamps for access, modification, and status changes
  • Inode information and filesystem location
  • SELinux security context

Stat is particularly valuable when you need to examine files at a deeper level than what’s possible with basic file commands. System administrators often use it for troubleshooting permission issues, verifying file integrity, and analyzing disk usage patterns. The command comes pre-installed on virtually all Linux distributions, making it universally accessible without additional setup.

Syntax and Basic Structure

The fundamental syntax of the stat command follows this pattern:

stat [OPTIONS] [FILE]

Where [OPTIONS] represents various flags that modify the command’s behavior, and [FILE] specifies the target file or directory path. If you run stat without specifying a filename, it will display an error message indicating that operands are missing.

The basic usage involves providing a path to the file you want to examine:

$ stat example_file.txt

This simple command returns a wealth of information about the file, presented in a structured format with labeled fields for easy interpretation. For directories, the syntax remains identical:

$ stat /home/user/documents

The stat command supports multiple file specification, allowing you to analyze several files in a single command:

$ stat file1.txt file2.txt directory1

Each file’s information will be displayed sequentially, making it convenient for batch analysis or comparison.

Understanding the Output Fields

When you run the stat command, it provides a comprehensive set of information fields. Let’s examine what each field represents:

File: Shows the complete name and path of the examined file.

Size: Indicates the file size in bytes.

Blocks: Displays how many blocks on the storage device are allocated to this file.

IO Block: Shows the filesystem’s block size used for input/output operations.

File type: Identifies whether the item is a regular file, directory, symbolic link, or other special file type.

Device: Displays the device number where the file resides, shown in both hexadecimal and decimal formats.

Inode: Presents the inode number, which uniquely identifies the file within its filesystem.

Links: Shows the number of hard links pointing to this file.

Access: Displays the file permissions in both octal (like 0664) and symbolic (like -rw-rw-r–) formats, along with the User ID (UID) and Group ID (GID).

Context: Shows the SELinux security context for the file when applicable.

Access time: Indicates when the file was last read or accessed.

Modify time: Shows when the file’s content was last changed.

Change time: Displays when the file’s metadata (permissions, ownership, etc.) was last modified.

Birth time: Records when the file was initially created (if the filesystem supports this data).

Understanding these fields helps you gain comprehensive insights into a file’s properties and history, which is invaluable for system administration and troubleshooting tasks.

Stat Command Options

The stat command offers several options that enhance its functionality for different scenarios. Here are the most useful flags:

Display File System Information (-f)

The -f option instructs stat to display information about the filesystem rather than the file itself:

$ stat -f example_file.txt

This command provides details such as:

  • File system ID in hexadecimal format
  • Maximum allowed length for filenames
  • File system block size
  • Total, free, and available blocks
  • Total and free inodes

This option is particularly valuable for disk space analysis and filesystem management tasks.

Follow Symbolic Links (-L)

By default, stat displays information about symbolic links themselves, not the files they point to. The -L option changes this behavior by following the link:

$ stat -L symbolic_link

This command shows information about the target file instead of the symbolic link, which is useful when you need to inspect the actual file properties.

Format Output (-c or –format)

The -c option allows you to customize the output format using format specifiers:

$ stat -c "%n %s %y" example_file.txt

This command displays only the filename (%n), size (%s), and modification time (%y), creating a more concise output focused on specific details.

Terse Output (-t)

For scripts and automation, the terse output option provides a compact, machine-readable format without headings or line breaks:

$ stat -t example_file.txt

This produces a single line of space-separated values, which is ideal for parsing with other command-line tools like awk or sed.

Custom Output Format (–printf)

The --printf option provides more control over formatting with escape sequence interpretation:

$ stat --printf="%s\n" example_file.txt

This command displays only the file size followed by a newline character, enabling precise control over output formatting.

Format Specifiers and Custom Output

Format specifiers are powerful tools for extracting specific information from the stat command. Here are some commonly used format specifiers:

  • %n – File name
  • %F – File type
  • %s – File size in bytes
  • %b – Number of blocks allocated
  • %u – User ID of owner
  • %U – User name of owner
  • %g – Group ID of owner
  • %G – Group name of owner
  • %a – Access rights in octal
  • %A – Access rights in human-readable form
  • %y – Last modification time
  • %x – Last access time
  • %z – Last change time
  • %w – Birth time (creation time)
  • %i – Inode number
  • %C – SELinux security context

You can combine multiple format specifiers to create custom outputs tailored to your needs:

$ stat -c "%A %h %U %G %s %y %n" file.txt

This command displays the file permissions, number of hard links, owner, group, size, modification time, and filename in a single line, mimicking the output of ls -l but with more control over the displayed fields.

For more complex formats with special characters, use the --printf option:

$ stat --printf="Name: %n\nSize: %s bytes\nModified: %y\n" file.txt

This creates labeled output with newlines between each field for better readability.

Example 1: Basic File Information

Let’s start with examining basic file information:

$ stat planets.xml
File: planets.xml
Size: 325       Blocks: 8          IO Block: 4096   regular file
Device: fd03h/64771d    Inode: 140217      Links: 1
Access: (0664/-rw-rw-r--)  Uid: (1000/tux)   Gid: (100/users)
Context: unconfined_u:object_r:user_home_t:s0
Access: 2024-08-17 18:26:57.281330711 +1200
Modify: 2024-08-17 18:26:58.738332799 +1200
Change: 2024-08-17 18:26:58.738332799 +1200
Birth: 2024-08-17 18:26:57.281330711 +1200

This output shows that planets.xml is a 325-byte regular file with read and write permissions for the owner and group, and read-only access for others. The file was last modified on August 17, 2021, and has only one hard link, indicating no duplicate references exist elsewhere on the filesystem.

Example 2: File System Information

To examine the filesystem where a file resides:

$ stat -f /home/user/documents
File: "/home/user/documents"
ID: 2f4a1234c5678d9e Namelen: 255     Type: ext4
Block size: 4096       Fundamental block size: 4096
Blocks: Total: 244190646  Free: 121634528  Available: 109008348
Inodes: Total: 62259200   Free: 60520320

This output provides valuable information about the filesystem, including its type (ext4), block size (4096 bytes), and disk space statistics. The “Available” blocks might differ from “Free” blocks due to reserved space for the root user. This information is crucial for monitoring disk usage and planning storage upgrades.

Example 3: Working with Multiple Files

Stat can efficiently process multiple files in a single command:

$ stat file1.txt file2.txt

Each file’s information will be displayed sequentially, allowing for quick comparison of properties like creation dates, permissions, or sizes. This functionality is particularly useful when verifying file consistency across backups or checking if a group of files shares the same ownership and permissions.

Example 4: Symbolic Links and Special Files

By default, stat shows information about the symbolic link itself:

$ stat /usr/local/bin/vim
File: /usr/local/bin/vim -> /usr/bin/vim
Size: 8         Blocks: 0          IO Block: 4096   symbolic link
Device: fd00h/64768d    Inode: 2883718     Links: 1
Access: (0777/lrwxrwxrwx)  Uid: (0/root)   Gid: (0/root)
Access: 2023-12-01 15:43:22.000000000 +0100
Modify: 2023-11-29 19:25:13.000000000 +0100
Change: 2023-11-29 19:25:13.000000000 +0100
Birth: -

Note that the first line indicates this is a symbolic link pointing to /usr/bin/vim.

To view information about the target file instead:

$ stat -L /usr/local/bin/vim

This output now shows details about the actual vim executable, not the symbolic link.

Example 5: Custom Format for Specific Information

When you need specific information for scripts or automation, custom formatting is invaluable:

$ stat -c "File: %n\nSize: %s bytes\nOwner: %U (%u)\nGroup: %G (%g)\nPermissions: %A\nModified: %y" important_file.txt

This command produces labeled output with only the most relevant information, making it perfect for reports or log entries. For even more precise control, you can combine stat with other commands:

$ stat -c "%s" large_file.txt | numfmt --to=iec

This pipes the file size to the numfmt utility, converting raw bytes to human-readable formats like KB, MB, or GB.

Real-World Applications

The stat command serves numerous practical purposes in system administration and everyday Linux usage:

File Integrity Verification

System administrators can use stat to verify file integrity by examining timestamps and permissions. Unexpected changes might indicate security breaches or unauthorized modifications. For critical system files, recording their stat output before and after system updates provides a simple but effective integrity check.

Security Auditing and Permissions Checking

Security professionals use stat for auditing file permissions and ownership to ensure proper access controls are in place. The detailed permission information, including SELinux context, helps identify security vulnerabilities like world-writable configuration files or executables with improper permissions.

Backup Management and Verification

When verifying backups, stat helps confirm that crucial file attributes like permissions and timestamps were properly preserved. This ensures that restored files will function correctly and maintain their original security context.

Disk Usage Analysis

The -f option provides valuable insights for disk space management by revealing filesystem statistics, block allocation, and inode usage. This information helps identify potential disk space issues before they become critical.

Timestamp Forensics

Digital forensics investigators use stat’s detailed timestamp information to establish file chronology and detect suspicious activity. The distinction between access, modification, and change times provides crucial evidence for reconstructing events during security incidents.

Comparison with Related Commands

Understanding how stat compares to other Linux commands helps you choose the right tool for each task:

stat vs. ls -l

While both commands display file information, stat provides more comprehensive metadata including detailed timestamps and inode information. The ls -l command offers a simpler, more condensed view that’s better for quick directory scanning, while stat excels at detailed file analysis.

stat vs. file

The file command focuses on determining file types by examining content, whereas stat displays metadata without analyzing the actual file contents. Use file when you need to identify file formats or detect binary versus text files, and stat when you need detailed metadata.

stat vs. find

Find is optimized for locating files based on criteria, while stat provides detailed information about known files. They complement each other well—use find to locate files of interest, then stat to analyze their properties in depth.

Best Practices and Tips

Follow these best practices to use stat effectively:

Performance Considerations

When dealing with large filesystems, be mindful that running stat on many files sequentially can be I/O intensive. For large-scale operations, consider using find with stat in a targeted manner rather than examining entire directories recursively.

Error Handling in Scripts

When incorporating stat in scripts, always include error handling for common issues like permission denied or non-existent files. For example:

if stat -t file.txt &>/dev/null; then
    size=$(stat -c "%s" file.txt)
    echo "File exists with size: $size bytes"
else
    echo "File not found or cannot be accessed"
fi

This approach prevents scripts from failing when encountering unexpected file conditions.

Security Implications

Remember that stat requires read permissions for the files it examines, but it doesn’t need to access file contents. This makes it relatively safe to use on sensitive files compared to commands that read file data. However, information disclosure is still a concern in multi-user environments.

Integration with Other Tools

Combine stat with other utilities to extend its capabilities:

# Find files modified in the last 24 hours and show their details
find /home/user -type f -mtime -1 -exec stat {} \;

This powerful combination helps identify recently changed files and examine their properties in detail.

Troubleshooting Common Issues

Even experienced Linux users occasionally encounter challenges with the stat command. Here are solutions to common problems:

Permission Denied Errors

When you encounter a “Permission denied” error:

stat: cannot stat '/root/file.txt': Permission denied

The solution is to either:

  1. Use sudo to elevate privileges: sudo stat /root/file.txt
  2. Adjust your account permissions if appropriate

Always be cautious when using elevated privileges, especially in production environments.

Non-existent File Handling

If you see a “No such file or directory” error:

stat: cannot stat 'missing.txt': No such file or directory

Verify the file path and check for typos. In scripts, you can add conditional logic to handle missing files gracefully:

[ -e "$file" ] && stat "$file" || echo "File not found: $file"

Filesystem Doesn’t Support Stat

Some specialized filesystems might not support all stat features, resulting in a “Function not implemented” error. In such cases, consider alternatives like ls -l for basic file information, or mount the filesystem with different options if possible.

Format String Syntax Errors

When using custom formats, syntax errors can cause unexpected output. Common mistakes include:

  • Missing quotes around format strings
  • Using incorrect format specifiers
  • Forgetting to escape certain characters when using –printf

Always test format strings with simple files before using them in production scripts.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button