Reading file metadata with stat
- Version
- unversioned
- Review
- Draft
Summary#
stat reports file metadata such as type, size, permissions and timestamps. With GNU stat, use -c to select fields for a script.
Syntax#
stat file
stat -c 'mode=%a bytes=%s' file
stat -L -c 'mode=%a bytes=%s' symbolic_link
%a prints permissions in octal, %s prints size in bytes and %F prints the file type.
Example#
(
set -eu
dir=$(mktemp -d)
trap 'rm -rf -- "$dir"' EXIT
cd "$dir"
printf 'ready\n' > status.txt
chmod 640 status.txt
ln -s status.txt latest
stat -c 'mode=%a bytes=%s' status.txt
LC_ALL=C stat -c '%F' latest
stat -L -c 'mode=%a bytes=%s' latest
)
Expected output#
mode=640 bytes=6
symbolic link
mode=640 bytes=6
Common mistakes#
By default stat examines a symbolic link itself. Use -L to examine its target. A file’s byte size can differ from the disk space it occupies.
Version applicability#
This entry uses GNU coreutils stat. macOS and BSD use stat -f with different format codes. On GNU stat, -f selects file system information.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0