Overview
The `stat` command shows a file's inode information (metadata). The `-c` option allows this information to be output in a user-defined format, making it suitable for extracting specific attributes or for use in combination with other commands.
Key Features
- View detailed metadata of files and file systems
- Supports user-defined output formats via the `-c` option
- Useful for scripts and automation tasks
- Access to various file attributes (size, permissions, owner, time, etc.)
Key Options
These are the main format specifiers used with the `-c` option, which is central to the `stat` command.
Format Specifier Options
Generated command:
Try combining the commands.
Description:
`stat` Executes the command.
Combine the above options to virtually execute commands with AI.
Usage Examples
Examples of using the `stat -c` option to output file information in various formats.
Output File Name and Size
stat -c '%n %s' my_file.txt
Outputs the name and size of the specified file, separated by a space.
Output File Type and Permissions
stat -c '%F %A' my_script.sh
Outputs the file's type and its human-readable permissions.
Output Owner, Group, and Last Modification Time
stat -c 'Owner: %U, Group: %G, Modified: %y' my_document.pdf
Outputs the file's owner name, group name, and last modification time along with specific strings.
Check Symbolic Link Target
stat -c '%N' my_symlink
For symbolic links, outputs the path to the original file that the link points to.
Output Name and Size for All Files/Directories in Current Directory
stat -c '%n %s' *
Uses a wildcard to output the name and size for all items in the current directory.
Tips & Notes
Tips and points to consider for more effective use of `stat -c`.
Using Quotes
If the FORMAT string contains spaces or special characters, it must be enclosed in single quotes (') or double quotes (") to prevent the shell from interpreting them as separate arguments.
- Single quotes ('): Useful for preventing variable expansion and passing the string literally.
- Double quotes ("): Used when you want to allow variable expansion while enclosing the string.
Time Formats
Time-related specifiers (%x, %y, %z) output in a human-readable format by default. Use %X, %Y, %Z to get the timestamp in seconds.
Combining with find Command
find . -maxdepth 1 -type f -exec stat -c '%n %s' {} \;
You can combine `stat -c` with the `find` command's `-exec` option to execute `stat -c` on files that meet specific criteria.
Operating System Differences
Some format specifiers may behave differently or not be supported depending on the operating system or `stat` version. For example, the `%w` (birth time) specifier is generally not supported on Linux and is only available on macOS/BSD.
- Linux: Typically uses the `stat` version included in the `coreutils` package.
- macOS/BSD: The behavior of some format specifiers (e.g., `%w`) may differ.