← Back to Bash Course | Chapter 9: File Testing & Filesystem | Lesson 13 of 13

stat

stat is like reading the details on a library card for a file: how big it is, who can use it and when it was last touched. It shows more than the quick look you get from ls.

In this page:

  1. stat
Syntax
bash
stat file_name

stat

stat reports detailed metadata about a file, including size, permissions, and timestamps, more comprehensively than ls -l.

Its exact output format differs slightly between Linux and macOS, but the core information it exposes is the same. It's often used in scripts that need to check things like file size or modification time programmatically.

Note: Use stat -c %s file on Linux to get just the file size in bytes, suitable for capturing in a variable.

Example: stat

bash
#!/bin/bash
echo "some sample content" > info.txt

stat info.txt

size=$(stat -c %s info.txt 2>/dev/null || stat -f %z info.txt)
echo "File size in bytes: $size"
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Assuming stat has the same options on Linux and macOS, since format flags differ.
  2. Forgetting the quotes around file names with spaces.
  3. Confusing modification time (content changed) with change time (metadata such as permissions changed).
Chapter Summary
  • File tests such as -f, -d, and -e check whether files and directories exist and what they are.
  • Reading, writing, appending, and line-by-line processing handle file contents, and globbing matches file names.
  • find, cp, mv, rm, directory operations, permissions, and stat manage the filesystem.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.