ZetCode

Linux stat and file Commands

last modified October 24, 2026

Two commands describe files without opening them in an editor. The stat command shows the metadata that the file system stores in the inode: size, owner, permissions, link count, and timestamps. The file command looks at the content and tells what kind of data the file holds, regardless of its name.

The examples were run on Debian 12 (GNU coreutils 9.1, file 5.44) in a container whose home directory is a freshly created ext4 file system.

Displaying file metadata

Without options, stat prints all metadata of a file.

echo "Hello there" > notes.txt
stat notes.txt

Size is the length in bytes, while Blocks counts the 512-byte units allocated on the disk: the 12-byte file occupies one 4096-byte file system block, which is 8 such units. IO Block is the preferred size for reads and writes. Device is the major and minor number of the device that holds the file system, Inode the number of the inode, and Links the number of hard links (names) of the file. Access shows the permissions in octal and symbolic form, followed by the owner and group.

The four timestamps are the last access (atime), the last modification of the content (mtime), the last change of the inode (ctime), and the creation time (birth). They have nanosecond precision and include the time zone offset.

$ echo "Hello there" > notes.txt
$ stat notes.txt
  File: notes.txt
  Size: 12        	Blocks: 8          IO Block: 4096   regular file
Device: 7,27	Inode: 36          Links: 1
Access: (0644/-rw-r--r--)  Uid: ( 1000/    jano)   Gid: ( 1000/    jano)
Access: 2026-10-24 21:15:27.981558946 +0200
Modify: 2026-10-24 21:15:27.981558946 +0200
Change: 2026-10-24 21:15:27.981558946 +0200
 Birth: 2026-10-24 21:15:27.981558946 +0200

Directories and symbolic links

stat describes the object it is given. For a symbolic link, that is the link itself, unless -L is used.

stat project
ln -s notes.txt link.txt
stat link.txt
stat -L link.txt

The project directory has 3 links: its entry in the parent directory, its own . entry, and the .. entry of its subdirectory src. The link count of a directory is therefore 2 plus the number of its subdirectories. The size of the symbolic link is 9, the length of the target name notes.txt; it has its own inode and uses no data blocks. With -L, stat follows the link and shows the target, inode 36.

$ stat project
  File: project
  Size: 4096      	Blocks: 8          IO Block: 4096   directory
Device: 7,27	Inode: 33          Links: 3
Access: (0755/drwxr-xr-x)  Uid: ( 1000/    jano)   Gid: ( 1000/    jano)
Access: 2026-10-24 21:15:27.981558946 +0200
Modify: 2026-10-24 21:15:27.981558946 +0200
Change: 2026-10-24 21:15:27.981558946 +0200
 Birth: 2026-10-24 21:15:27.981558946 +0200
$ ln -s notes.txt link.txt
$ stat link.txt
  File: link.txt -> notes.txt
  Size: 9         	Blocks: 0          IO Block: 4096   symbolic link
Device: 7,27	Inode: 37          Links: 1
Access: (0777/lrwxrwxrwx)  Uid: ( 1000/    jano)   Gid: ( 1000/    jano)
Access: 2026-10-24 21:15:27.984558985 +0200
Modify: 2026-10-24 21:15:27.984558985 +0200
Change: 2026-10-24 21:15:27.984558985 +0200
 Birth: 2026-10-24 21:15:27.984558985 +0200
$ stat -L link.txt
  File: link.txt
  Size: 12        	Blocks: 8          IO Block: 4096   regular file
Device: 7,27	Inode: 36          Links: 1
Access: (0644/-rw-r--r--)  Uid: ( 1000/    jano)   Gid: ( 1000/    jano)
Access: 2026-10-24 21:15:27.981558946 +0200
Modify: 2026-10-24 21:15:27.981558946 +0200
Change: 2026-10-24 21:15:27.981558946 +0200
 Birth: 2026-10-24 21:15:27.981558946 +0200

Device files

Device files have no size; instead, they carry the major and minor device numbers through which the kernel finds the driver.

stat /dev/null
ls -l /dev/null

Device type: 1,3 is the major number 1 (memory devices) and the minor number 3 (null). ls -l shows the same pair in place of the size.

$ stat /dev/null
  File: /dev/null
  Size: 0         	Blocks: 0          IO Block: 4096   character special file
Device: 0,69	Inode: 138         Links: 1     Device type: 1,3
Access: (0666/crw-rw-rw-)  Uid: (    0/    root)   Gid: (    0/    root)
Access: 2026-10-24 21:15:27.858557320 +0200
Modify: 2026-10-24 21:15:27.858557320 +0200
Change: 2026-10-24 21:15:27.858557320 +0200
 Birth: 2026-10-24 21:15:27.858557320 +0200
$ ls -l /dev/null
crw-rw-rw- 1 root root 1, 3 Oct 24 21:15 /dev/null

Custom output with format strings

The -c (--format) option prints only the requested fields. It is the way to get file metadata into scripts.

stat -c '%n %s %U %a %A' notes.txt /etc/passwd /etc/shadow
stat -c %s notes.txt
stat -c '%n is a %F owned by %U:%G' notes.txt project link.txt
stat --printf '%n\t%s\n' notes.txt /etc/passwd

%n is the file name, %s the size, %U and %G the owner and group names, %a the octal permissions, %A the symbolic ones, and %F the file type. -c adds a newline after each file. --printf does not, but it interprets backslash escapes such as \t and \n. Note that %n means the name, not a newline. Reading the metadata of /etc/shadow does not require read permission on the file, only search permission on the directory.

$ stat -c '%n %s %U %a %A' notes.txt /etc/passwd /etc/shadow
notes.txt 12 jano 644 -rw-r--r--
/etc/passwd 963 root 644 -rw-r--r--
/etc/shadow 546 root 640 -rw-r-----
$ stat -c %s notes.txt
12
$ stat -c '%n is a %F owned by %U:%G' notes.txt project link.txt
notes.txt is a regular file owned by jano:jano
project is a directory owned by jano:jano
link.txt is a symbolic link owned by jano:jano
$ stat --printf '%n\t%s\n' notes.txt /etc/passwd
notes.txt	12
/etc/passwd	963

Format sequences

The most useful format sequences are listed in the following table; see man stat for the complete list.

SequenceMeaning
%nFile name
%sSize in bytes
%a, %APermissions in octal and symbolic form
%U, %uOwner name and UID
%G, %gGroup name and GID
%FFile type
%i, %hInode number, number of hard links
%x, %y, %z, %wAccess, modification, change, birth time
%X, %Y, %Z, %WThe same as seconds since the epoch
%NQuoted name, with the target for symbolic links

Modification time and change time

mtime and ctime are often confused. mtime changes when the content changes; ctime changes whenever anything in the inode changes, including permissions, owner, link count, and mtime itself.

stat --printf 'mtime %y\nctime %z\n' notes.txt
sleep 2; chmod 600 notes.txt
stat --printf 'mtime %y\nctime %z\n' notes.txt
sleep 2; echo "Second line" >> notes.txt
stat --printf 'mtime %y\nctime %z\n' notes.txt
touch -d '2025-01-01 12:00' notes.txt
stat --printf 'mtime %y\nctime %z\n' notes.txt

chmod changed only the ctime. Appending a line changed both. touch -d can set mtime to any value, but the change itself updated the ctime to the current time. Programs cannot set ctime, which makes it useful for detecting that a file was touched. Backup tools and make use mtime; see the touch article.

$ stat --printf 'mtime %y\nctime %z\n' notes.txt
mtime 2026-10-24 21:15:27.981558946 +0200
ctime 2026-10-24 21:15:27.981558946 +0200
$ sleep 2; chmod 600 notes.txt
$ stat --printf 'mtime %y\nctime %z\n' notes.txt
mtime 2026-10-24 21:15:27.981558946 +0200
ctime 2026-10-24 21:15:29.999585617 +0200
$ sleep 2; echo "Second line" >> notes.txt
$ stat --printf 'mtime %y\nctime %z\n' notes.txt
mtime 2026-10-24 21:15:32.006612143 +0200
ctime 2026-10-24 21:15:32.006612143 +0200
$ touch -d '2025-01-01 12:00' notes.txt
$ stat --printf 'mtime %y\nctime %z\n' notes.txt
mtime 2025-01-01 12:00:00.000000000 +0100
ctime 2026-10-24 21:15:32.015612262 +0200

Access time and relatime

Updating the access time on every read would turn each read into a write. Linux file systems are therefore mounted with relatime by default.

findmnt -no OPTIONS /home/jano
stat -c 'atime %x' notes.txt
cat notes.txt > /dev/null
stat -c 'atime %x' notes.txt
sleep 2; cat notes.txt > /dev/null
stat -c 'atime %x' notes.txt

With relatime, the atime is updated only if it is older than the mtime or ctime, or more than 24 hours old. The first cat updated it; the second, two seconds later, did not. The atime thus tells whether a file has been read since its last change, or during the last day, but not exactly when it was last read.

$ findmnt -no OPTIONS /home/jano
rw,relatime
$ stat -c 'atime %x' notes.txt
atime 2025-01-01 12:00:00.000000000 +0100
$ cat notes.txt > /dev/null
$ stat -c 'atime %x' notes.txt
atime 2026-10-24 21:15:32.031612474 +0200
$ sleep 2; cat notes.txt > /dev/null
$ stat -c 'atime %x' notes.txt
atime 2026-10-24 21:15:32.031612474 +0200

Timestamps in seconds

The uppercase sequences print timestamps as seconds since the Unix epoch, which is easy to compare and compute with.

stat -c '%Y %n' notes.txt project/src/main.c
date -d @$(stat -c %Y notes.txt)
echo "$(( $(date +%s) - $(stat -c %Y project/src/main.c) )) seconds old"
date -r notes.txt '+%F %T'

date -d @SECONDS converts the number back to a date. The third command computes the age of a file in seconds. GNU date -r prints the mtime of a file directly, in any format.

$ stat -c '%Y %n' notes.txt project/src/main.c
1735729200 notes.txt
1792869327 project/src/main.c
$ date -d @$(stat -c %Y notes.txt)
Wed Jan  1 12:00:00 PM CET 2025
$ echo "$(( $(date +%s) - $(stat -c %Y project/src/main.c) )) seconds old"
7 seconds old
$ date -r notes.txt '+%F %T'
2025-01-01 12:00:00

Inodes and hard links

A hard link is another name for the same inode. stat shows the inode number and the link count.

ln notes.txt hard.txt
stat -c '%n inode=%i links=%h' notes.txt hard.txt link.txt
ls -li notes.txt hard.txt link.txt
stat -c '%n links=%h' project project/src

notes.txt and hard.txt share inode 36, and its link count is now 2. The symbolic link has its own inode. ls -i shows the inode numbers in the first column. The directory src has no subdirectories, so its count is 2. See the ln article for more on links.

$ ln notes.txt hard.txt
$ stat -c '%n inode=%i links=%h' notes.txt hard.txt link.txt
notes.txt inode=36 links=2
hard.txt inode=36 links=2
link.txt inode=37 links=1
$ ls -li notes.txt hard.txt link.txt
36 -rw------- 2 jano jano 24 Jan  1  2025 hard.txt
37 lrwxrwxrwx 1 jano jano  9 Oct 24 21:15 link.txt -> notes.txt
36 -rw------- 2 jano jano 24 Jan  1  2025 notes.txt
$ stat -c '%n links=%h' project project/src
project links=3
project/src links=2

File system information

With -f, stat describes the file system that contains the file instead of the file.

stat -f .
stat -f -c 'type=%T block=%S total=%b free=%f avail=%a inodes=%c' .
stat -f -c %T /dev/shm /proc /

stat -f reports ext4 as ext2/ext3, because the three share the same magic number. The block counts are in file system blocks. Free includes the blocks reserved for root; Available is what regular users can use, the value that df shows. The last command shows the types of three other file systems: the shared memory tmpfs, the proc pseudo file system, and the container's overlay root.

$ stat -f .
  File: "."
    ID: cc81499b914ee0c5 Namelen: 255     Type: ext2/ext3
Block size: 4096       Fundamental block size: 4096
Blocks: Total: 124725     Free: 124692     Available: 115518
Inodes: Total: 32768      Free: 32731
$ stat -f -c 'type=%T block=%S total=%b free=%f avail=%a inodes=%c' .
type=ext2/ext3 block=4096 total=124725 free=124692 avail=115518 inodes=32768
$ stat -f -c %T /dev/shm /proc /
tmpfs
proc
overlayfs

Using stat in a script

The following script checks backup files: it reports files that are missing, older than a day, or suspiciously small.

check-backup.sh
#!/bin/bash

# warns about backup files that are missing, too old, or too small
max_age=$((24 * 60 * 60))
min_size=1000

now=$(date +%s)

for f in "$@"; do
    if [ ! -e "$f" ]; then
        echo "$f: missing"
        continue
    fi

    age=$(( now - $(stat -c %Y "$f") ))
    size=$(stat -c %s "$f")

    if [ "$age" -gt "$max_age" ]; then
        echo "$f: too old ($(( age / 3600 )) hours)"
    elif [ "$size" -lt "$min_size" ]; then
        echo "$f: too small ($size bytes)"
    else
        echo "$f: OK ($size bytes, modified $(date -d @"$(stat -c %Y "$f")" '+%F %H:%M'))"
    fi
done

stat -c %Y gives the modification time and stat -c %s the size; both are plain numbers that Bash arithmetic can compare. The file names are quoted, so they may contain spaces.

$ cat check-backup.sh
#!/bin/bash

# warns about backup files that are missing, too old, or too small
max_age=$((24 * 60 * 60))
min_size=1000

now=$(date +%s)

for f in "$@"; do
    if [ ! -e "$f" ]; then
        echo "$f: missing"
        continue
    fi

    age=$(( now - $(stat -c %Y "$f") ))
    size=$(stat -c %s "$f")

    if [ "$age" -gt "$max_age" ]; then
        echo "$f: too old ($(( age / 3600 )) hours)"
    elif [ "$size" -lt "$min_size" ]; then
        echo "$f: too small ($size bytes)"
    else
        echo "$f: OK ($size bytes, modified $(date -d @"$(stat -c %Y "$f")" '+%F %H:%M'))"
    fi
done
$ ls -l backup.tar db.sql config.tar
-rw-r--r-- 1 jano jano 2000000 Oct 21 21:15 backup.tar
-rw-r--r-- 1 jano jano     300 Oct 24 21:15 config.tar
-rw-r--r-- 1 jano jano 1500000 Oct 24 19:15 db.sql
$ bash check-backup.sh backup.tar db.sql config.tar missing.tar
backup.tar: too old (72 hours)
db.sql: OK (1500000 bytes, modified 2026-10-24 19:15)
config.tar: too small (300 bytes)
missing.tar: missing

Determining the file type

The file command reads the beginning of a file and compares it with a database of known signatures (magic numbers). For text, it also checks the character encoding and line endings.

cd samples
file report.pdf photo.jpg users.csv backup.sh
file *

Besides the type, file reports details that it finds in the headers, such as the PDF version and page count, or the JPEG resolution and image size. Text files are reported with their encoding: ASCII, UTF-8, ISO-8859, or UTF-16. noshebang.py is a Python program, but without a #! line it is reported as plain text.

$ cd samples
$ file report.pdf photo.jpg users.csv backup.sh
report.pdf: PDF document, version 1.5, 1 pages
photo.jpg:  JPEG image data, JFIF standard 1.01, resolution (DPI), density 50x50, segment length 16, baseline, precision 8, 445x570, components 3
users.csv:  CSV text
backup.sh:  Bourne-Again shell script, ASCII text executable
$ file *
backup.sh:           Bourne-Again shell script, ASCII text executable
empty.txt:           empty
greeting-latin2.txt: ISO-8859 text
greeting.txt:        Unicode text, UTF-8 text
greeting-utf16.txt:  Unicode text, UTF-16, little-endian text
hello.py:            Python script, ASCII text executable
index.html:          HTML document, ASCII text
noshebang.py:        ASCII text
photo.jpg:           JPEG image data, JFIF standard 1.01, resolution (DPI), density 50x50, segment length 16, baseline, precision 8, 445x570, components 3
report.pdf:          PDF document, version 1.5, 1 pages
user.json:           JSON text data
users.csv:           CSV text
users.xml:           XML 1.0 document, ASCII text
windows.txt:         ASCII text, with CRLF line terminators

File names do not matter

file ignores the extension. This makes it useful for checking uploads and files with wrong or missing extensions.

cp photo.jpg holiday.txt
cp report.pdf invoice.jpg
file holiday.txt invoice.jpg
file -b holiday.txt

The image named .txt is still a JPEG, and the PDF named .jpg is still a PDF. The -b (brief) option omits the file name, which is convenient in scripts.

$ cp photo.jpg holiday.txt
$ cp report.pdf invoice.jpg
$ file holiday.txt invoice.jpg
holiday.txt: JPEG image data, JFIF standard 1.01, resolution (DPI), density 50x50, segment length 16, baseline, precision 8, 445x570, components 3
invoice.jpg: PDF document, version 1.5, 1 pages
$ file -b holiday.txt
JPEG image data, JFIF standard 1.01, resolution (DPI), density 50x50, segment length 16, baseline, precision 8, 445x570, components 3

MIME types and encodings

The --mime-type option prints a MIME type instead of a description, and -i (--mime) adds the character set.

file --mime-type photo.jpg report.pdf users.csv user.json backup.sh empty.txt
file -i greeting.txt greeting-latin2.txt greeting-utf16.txt
file -b --mime-encoding greeting-latin2.txt

MIME types are stable and short, so scripts should test them rather than the human-readable descriptions. Encoding detection has limits: the file was written in ISO-8859-2 (Central European), but file reports iso-8859-1. The single-byte ISO-8859 encodings use the same byte ranges, so the content alone does not tell them apart.

$ file --mime-type photo.jpg report.pdf users.csv user.json backup.sh empty.txt
photo.jpg:  image/jpeg
report.pdf: application/pdf
users.csv:  text/csv
user.json:  application/json
backup.sh:  text/x-shellscript
empty.txt:  inode/x-empty
$ file -i greeting.txt greeting-latin2.txt greeting-utf16.txt
greeting.txt:        text/plain; charset=utf-8
greeting-latin2.txt: text/plain; charset=iso-8859-1
greeting-utf16.txt:  text/plain; charset=utf-16le
$ file -b --mime-encoding greeting-latin2.txt
iso-8859-1

Fixing encodings and line endings

When file reports a legacy encoding or CRLF line terminators, the file can be converted.

file greeting-latin2.txt windows.txt
iconv -f ISO-8859-2 -t UTF-8 greeting-latin2.txt > fixed.txt
file fixed.txt
cmp fixed.txt greeting.txt && echo same
sed 's/\r$//' windows.txt > unix.txt
file unix.txt

iconv converts between encodings; we have to tell it the real source encoding, which file could not determine. The result is identical to the original UTF-8 file. Windows line endings (\r\n) break shell scripts and some tools; sed removes the carriage returns.

$ file greeting-latin2.txt windows.txt
greeting-latin2.txt: ISO-8859 text
windows.txt:         ASCII text, with CRLF line terminators
$ iconv -f ISO-8859-2 -t UTF-8 greeting-latin2.txt > fixed.txt
$ file fixed.txt
fixed.txt: Unicode text, UTF-8 text
$ cmp fixed.txt greeting.txt && echo same
same
$ sed 's/\r$//' windows.txt > unix.txt
$ file unix.txt
unix.txt: ASCII text

Symbolic links and special files

Like stat, file describes a symbolic link itself unless -L is given.

ln -s report.pdf latest.pdf
file latest.pdf
file -L latest.pdf
file /bin/sh
file -L /bin/sh
file /dev/null /dev/stdin

On Debian, /bin/sh is a link to dash, an ELF executable. For device files, file prints the type and the device numbers.

$ ln -s report.pdf latest.pdf
$ file latest.pdf
latest.pdf: symbolic link to report.pdf
$ file -L latest.pdf
latest.pdf: PDF document, version 1.5, 1 pages
$ file /bin/sh
/bin/sh: symbolic link to dash
$ file -L /bin/sh
/bin/sh: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=be6397ddffc3e384c505d7deab3bed190c884df9, for GNU/Linux 3.2.0, stripped
$ file /dev/null /dev/stdin
/dev/null:  character special (1/3)
/dev/stdin: symbolic link to /proc/self/fd/0

Archives and compressed files

file recognizes archives, compressed data, and many binary formats. The -z option also looks inside compressed files.

gzip -k users.csv
tar -cf docs.tar report.pdf users.xml
xz -k docs.tar
zip -q bundle.zip index.html user.json
python3 -c 'import sqlite3; sqlite3.connect("app.db").execute("create table t(x)")'
file users.csv.gz docs.tar docs.tar.xz bundle.zip app.db
file -z users.csv.gz docs.tar.xz

For gzip, file shows the stored original name and time (in UTC) and the size. With -z, it reports that the gzip file holds CSV text and the xz file a tar archive. The SQLite database is recognized, including the version of the library that wrote it.

$ gzip -k users.csv
$ tar -cf docs.tar report.pdf users.xml
$ xz -k docs.tar
$ zip -q bundle.zip index.html user.json
$ python3 -c 'import sqlite3; sqlite3.connect("app.db").execute("create table t(x)")'
$ file users.csv.gz docs.tar docs.tar.xz bundle.zip app.db
users.csv.gz: gzip compressed data, was "users.csv", last modified: Sat Oct 24 19:14:04 2026, from Unix, original size modulo 2^32 48
docs.tar:     POSIX tar archive (GNU)
docs.tar.xz:  XZ compressed data, checksum CRC64
bundle.zip:   Zip archive data, at least v2.0 to extract, compression method=deflate
app.db:       SQLite 3.x database, last written using SQLite version 3040001, file counter 1, database pages 2, cookie 0x1, schema 4, UTF-8, version-valid-for 1
$ file -z users.csv.gz docs.tar.xz
users.csv.gz: CSV text (gzip compressed data, was "users.csv", last modified: Sat Oct 24 19:14:04 2026, from Unix)
docs.tar.xz:  POSIX tar archive (GNU) (XZ compressed data, checksum CRC64)

Scripts

For scripts, file reads the #! line (shebang).

head -n 1 backup.sh hello.py noshebang.py
file backup.sh hello.py noshebang.py
file /usr/bin/zgrep /usr/bin/pydoc3

#!/bin/bash gives a Bourne-Again shell script and #!/usr/bin/env python3 a Python script. Many commands in /usr/bin are scripts rather than compiled programs: zgrep is a shell script.

$ head -n 1 backup.sh hello.py noshebang.py
==> backup.sh <==
#!/bin/bash

==> hello.py <==
#!/usr/bin/env python3

==> noshebang.py <==
print("no shebang")
$ file backup.sh hello.py noshebang.py
backup.sh:    Bourne-Again shell script, ASCII text executable
hello.py:     Python script, ASCII text executable
noshebang.py: ASCII text
$ file /usr/bin/zgrep /usr/bin/pydoc3
/usr/bin/zgrep:  POSIX shell script, ASCII text executable
/usr/bin/pydoc3: symbolic link to pydoc3.11

Finding files by type

Combined with find, file locates files by their content.

cd ~/work
find . -type f -exec file --mime-type {} + | grep -v 'text/'
find /usr/bin -type f -exec file {} + | grep -c 'shell script'

The first command lists all files that are not text. Files filled with zero bytes have no recognizable structure and are reported as application/octet-stream, that is, generic binary data. The second command counts the shell scripts in /usr/bin. The + form of -exec passes many files to one file process.

$ cd ~/work
$ find . -type f -exec file --mime-type {} + | grep -v 'text/'
./backup.tar:                  application/octet-stream
./db.sql:                      application/octet-stream
./config.tar:                  application/octet-stream
./samples/report.pdf:          application/pdf
./samples/user.json:           application/json
./samples/docs.tar:            application/x-tar
./samples/users.csv.gz:        application/gzip
./samples/empty.txt:           inode/x-empty
./samples/docs.tar.xz:         application/x-xz
./samples/photo.jpg:           image/jpeg
./samples/bundle.zip:          application/zip
./samples/app.db:              application/vnd.sqlite3
$ find /usr/bin -type f -exec file {} + | grep -c 'shell script'
67

Using file in a script

The following script classifies files by their MIME type.

sort-files.sh
#!/bin/bash

# reports what to do with each file, based on its MIME type, not its name
for f in "$1"/*; do
    [ -f "$f" ] || continue
    type=$(file -b --mime-type "$f")

    case $type in
        image/*)          echo "image:    $f" ;;
        application/pdf)  echo "document: $f" ;;
        text/x-shellscript | text/x-script.python)
                          echo "script:   $f" ;;
        text/*)           echo "text:     $f" ;;
        *)                echo "other:    $f ($type)" ;;
    esac
done

case patterns such as image/* match whole families of types. The script trusts the content, not the extension. latest.pdf is reported as inode/symlink, because file does not follow links; add -L to classify the targets.

$ cat sort-files.sh
#!/bin/bash

# reports what to do with each file, based on its MIME type, not its name
for f in "$1"/*; do
    [ -f "$f" ] || continue
    type=$(file -b --mime-type "$f")

    case $type in
        image/*)          echo "image:    $f" ;;
        application/pdf)  echo "document: $f" ;;
        text/x-shellscript | text/x-script.python)
                          echo "script:   $f" ;;
        text/*)           echo "text:     $f" ;;
        *)                echo "other:    $f ($type)" ;;
    esac
done
$ bash sort-files.sh samples
other:    samples/app.db (application/vnd.sqlite3)
script:   samples/backup.sh
other:    samples/bundle.zip (application/zip)
other:    samples/docs.tar (application/x-tar)
other:    samples/docs.tar.xz (application/x-xz)
other:    samples/empty.txt (inode/x-empty)
text:     samples/fixed.txt
text:     samples/greeting-latin2.txt
text:     samples/greeting.txt
text:     samples/greeting-utf16.txt
script:   samples/hello.py
text:     samples/index.html
other:    samples/latest.pdf (inode/symlink)
text:     samples/noshebang.py
image:    samples/photo.jpg
document: samples/report.pdf
text:     samples/unix.txt
other:    samples/user.json (application/json)
text:     samples/users.csv
other:    samples/users.csv.gz (application/gzip)
text:     samples/users.xml
text:     samples/windows.txt

GNU and BSD stat

The stat command on macOS and the BSDs has different options: -f takes a format string there, and the sequences differ, for example stat -f %z file for the size. Scripts that must run on both systems can use wc -c < file for the size. file behaves the same on all systems, since it is one project.

Best practices

Source

GNU coreutils: stat invocation, file(1) manual page

In this article, we have used stat to read file metadata, format it for scripts, understand the four timestamps, and look at inodes, links, and file systems, and file to identify file types, MIME types, encodings, and archives. See also the ls, touch, and find articles.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Linux tutorials.