About the stat Command
The stat command displays detailed information about files and filesystems. Unlike ls which shows basic file listings, stat reveals comprehensive metadata including inode numbers, permissions in multiple formats, timestamps (access, modification, change), file size in bytes and blocks, device information, and more. It's an essential diagnostic tool for system administrators, forensics, and troubleshooting file-related issues.
Key capabilities: Display file metadata, show inode information, reveal all three timestamps (atime, mtime, ctime), format output for scripting, query filesystem information, follow or not follow symbolic links, and provide machine-readable output.
Detailed Examples
1Basic File Information
Display comprehensive information about a file.
2Custom Format Output
Extract specific information using format strings.
-c flag allows custom format strings. First example: Shows just filename and size in a concise format. Second example: Multi-line custom output with labels. Newlines in the format string are preserved. Third example: CSV-style output for multiple files - perfect for importing into spreadsheets or databases. Format sequences like %n (name), %s (size), %y (modify time) extract specific fields. Scripting power: Custom formats make stat output parseable by scripts. Instead of parsing human-readable output, you can extract exact fields needed. This is essential for automation, monitoring, and data collection scripts.
stat -c "%n,%s,%Y" * where %Y gives Unix timestamp (seconds since epoch) instead of human-readable time - perfect for date calculations.3Terse Output for Scripting
Machine-readable format for automated processing.
-t (terse) flag outputs all information in a single line with space-separated fields - ideal for parsing with awk, cut, or other text processing tools. Field order: name, size, blocks, mode (hex), uid, gid, device, inode, links, major, minor, atime, mtime, ctime, birth, blocksize. Second example: Shows parsing terse output with awk. Fields are positional: $1=name, $2=size, $5=uid, etc. Why terse mode: Consistent field positions make parsing reliable. Human-readable format varies and is hard to parse. Terse format is stable and designed for scripts. Use case: Collecting file statistics across many files for analysis, generating reports, or monitoring file changes over time.
4Comparing File Timestamps
Understanding and working with the three timestamps.
find . -type f -mtime -1 (last 24 hours) or check specific times with stat to verify backups, deployments, or changes.5Filesystem Information
Query filesystem details instead of file details.
-f flag shows filesystem information instead of file information. Output details: ID is the filesystem ID, Namelen is maximum filename length, Type shows filesystem type (ext4, xfs, btrfs, etc.), Block size information, Total/Free/Available blocks (Available accounts for reserved blocks), Total/Free inodes. Second example: Custom format for filesystem stats. %n = path, %T = type, %a = available blocks, %b = total blocks. Use cases: Monitoring disk space at filesystem level, checking filesystem type before operations, verifying mount points, capacity planning, and troubleshooting space issues. Available vs Free: "Free" is total unused space, "Available" is what non-root users can use (some space is reserved for root).
stat -fc "$(echo ~)/: %a/%b = $((100*%a/%b))% free" ~ calculates percentage free space.6Symbolic Links
Examining symbolic links vs. their targets.
7Scripting: Find Large Files
Using stat in scripts to analyze file characteristics.
find locates all files (null-separated for safety with special characters). Step 2: stat -c %s extracts exact size in bytes. Step 3: Compare against threshold. Step 4: For large files, convert size to human-readable format with numfmt and print. Step 5: Sort by size (largest first) using sort -rh. Why stat instead of ls: Stat gives precise byte counts and is more scriptable. stat -c %s is cleaner than parsing ls -l output. Practical uses: Disk space analysis, finding bloat, identifying files to archive, capacity planning, and quota management.
find . -type f | while read f; do echo "$(stat -c %Y "$f") $f"; done | sort -rn sorts by modification timestamp.8Scripting: Verify Backup Integrity
Compare files using stat to verify backups.
stat -c %a, verify ownership, or check inode numbers for hard links. Real-world use: Automated backup verification, disaster recovery prep, compliance checking, and ensuring backups are current before critical operations.
9Monitoring File Changes
Track when files were last modified for monitoring.
%Y gives Unix timestamp (seconds since epoch) for easy calculations. %y gives human-readable format for logging. Run this via cron to track config changes over time. Second script: Checks if a critical file (/etc/passwd) was modified recently. Calculates age by subtracting file mtime from current time. If modified in last hour (3600 seconds), triggers alert. Use cases: Security monitoring (unauthorized changes to system files), compliance auditing (who changed what when), change management (tracking configuration updates), and troubleshooting (correlating file changes with system issues).
inotifywait -m /etc/nginx/nginx.conf watches for changes immediately rather than polling.10Advanced: Inode and Hard Link Analysis
Understanding inodes and finding hard links.
%i = inode, %d = device (important: inodes are unique per device, not globally). find -inum locates all files with that inode. -xdev prevents crossing filesystems. Why this matters: Hard links save space (one copy of data, multiple names), but can be confusing. Deleting one hard link doesn't delete the data until all links are removed. Stat reveals the link count, helping understand file relationships. Use cases: Space analysis, understanding backup structures, file deduplication verification, and troubleshooting "file won't delete" issues.
Format Sequences Reference
| Format | Description | Example Output |
|---|---|---|
%n |
File name | example.txt |
%N |
Quoted file name with dereferencing if symlink | 'link' -> 'target' |
%s |
Total size in bytes | 1024 |
%b |
Number of blocks allocated | 8 |
%F |
File type | regular file |
%a |
Access rights in octal | 644 |
%A |
Access rights in human-readable form | -rw-r--r-- |
%u |
User ID of owner | 1000 |
%U |
User name of owner | craig |
%g |
Group ID | 1000 |
%G |
Group name | users |
%x |
Time of last access | 2025-11-28 10:00:00.000000000 -0500 |
%X |
Time of last access (Unix timestamp) | 1732806000 |
%y |
Time of last modification | 2025-11-28 09:55:00.000000000 -0500 |
%Y |
Time of last modification (Unix timestamp) | 1732805700 |
%z |
Time of last status change | 2025-11-28 09:55:00.000000000 -0500 |
%Z |
Time of last status change (Unix timestamp) | 1732805700 |
%i |
Inode number | 12345678 |
%h |
Number of hard links | 1 |
Common Use Cases
Quick Size Check
Permission Verification
Find Recently Modified Files
Check if File Changed Today
Related Commands
- ls: List directory contents with basic file info
- file: Determine file type by examining contents
- find: Search for files and can execute stat on results
- df: Report filesystem disk space usage
- du: Estimate file and directory space usage
- lsattr/chattr: List/change file attributes on Linux
- touch: Change file timestamps
- chmod/chown: Change permissions/ownership (which stat displays)