Count Files in a Directory: Why Each Method Disagrees

Updated

Linux terminal showing a file listing

Count files in the current directory with find . -maxdepth 1 -type f -print0 | tr -dc '\0' | wc -c, and the whole tree below it with the same command minus -maxdepth 1. Every shorter one-liner answers a different question. On one scratch directory holding 6 files (2 of them hidden), 2 subdirectories and 8 files in the tree, here is what each of these commands returned:

ls | wc -l                            7
ls -A | wc -l                         9
ls -a | wc -l                        11
find . -type f | wc -l                9
find . -maxdepth 1 -type f | wc -l    7
stat -c %h .                          stat: illegal option -- c

find . -maxdepth 1 -type f -print0 | tr -dc '\0' | wc -c    6   <-- the file count

Five commands, three different numbers and one hard error, and not one of them is 6. The newline in one filename inflates every | wc -l count by exactly one; everything else — subdirectories counted as files, hidden entries in or out, the whole tree instead of this directory — is a separate error stacked on top of that.

stat does not count files

Using stat -c %h . to count files in a directory is wrong in two ways.

First, -c is GNU syntax. On macOS and the BSDs it is a hard error, as above; the local spelling is stat -f %l. Second, and fatally: %h is the directory's hard-link count. It is not a count of files under any implementation. GNU findutils find(1), explaining its -noleaf option, states the convention plainly: "Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory." Subdirectories. Not files. Follow that convention and a directory holding ten thousand plain files and no subdirectories has a link count of 2 — an inference from the quoted rule, not something measured here.

APFS does not follow that convention at all, which is measurable here in three lines:

empty directory             link count 2
directory with 3 files      link count 5
directory with 2 subdirs    link count 4

On APFS the link count is the number of child entries plus two, files included. Measured on a directory holding 50,000 plain files and 50 subdirectories, stat -f %l returned 50052; under the Unix convention quoted above the same directory would report 52. Neither number is the file count, and the two platforms are not even wrong in the same direction. GNU's own manual flags this class of filesystem as the reason -noleaf exists: "This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points." The Linux half of this paragraph is cited from that manual, not run on Linux. The scratch directory behind the first table — 6 files, 2 of them hidden and one named with a newline, plus 2 subdirectories — is rebuilt by count-files-in-directory.sh, which re-checks those counts and reports which link-count convention the filesystem it runs on follows.

The accurate method was also the fast one

On a directory of 50,000 plain files and 50 subdirectories, timed one run each with time -p:

ls | wc -l                                                   count=50050 real=0.15s
ls -A | wc -l                                                count=50050 real=0.20s
ls -f | wc -l                                                count=50052 real=0.07s
find . -maxdepth 1 -type f | wc -l                           count=50000 real=0.07s
find . -maxdepth 1 -type f -print0 | tr -dc '\0' | wc -c     count=50000 real=0.07s

The slowest method is the inaccurate one. ls sorts before printing and find does not, which is most of the difference; ls -f skips the sort and matches find's time but adds . and .. and still counts the 50 directories. Single runs on a warm cache — the ordering is the point, not the hundredths.

Decide what you are counting first

Three genuinely different questions get conflated in every guide to this:

  • Files in this directory — find . -maxdepth 1 -type f -print0 | tr -dc '\0' | wc -c
  • Files in the whole tree — drop -maxdepth 1. Above, that is 8 rather than 6.
  • Entries, including subdirectories — find . -maxdepth 1 -mindepth 1 -print0 | tr -dc '\0' | wc -c. -mindepth 1 is what stops . itself being counted.

Add -name '*.log' for one file type. Hidden files are included by all three; to exclude them, add ! -name '.*'.

Why tr -dc '\0' | wc -c rather than wc -l: -print0 separates names with a NUL byte, the only character a filename may not contain. tr discards everything except those separators and wc -c counts them, so a name containing a newline counts once instead of twice — the discrepancy between the 7 and the 6 above. The ls command page covers why ls output cannot be counted or parsed at all.

A script that counts files in a directory

A script built on COUNT=$(find "$DIR" -type f | wc -l) behind a [ -d "$DIR" ] test counts the entire tree, not just the directory, and miscounts any name containing a newline. Corrected:

#!/bin/bash
dir=${1:-.}
[ -d "$dir" ] || { printf 'Not a directory: %s\n' "$dir" >&2; exit 1; }
here=$(find "$dir" -maxdepth 1 -type f -print0 | tr -dc '\0' | wc -c)
tree=$(find "$dir" -type f -print0 | tr -dc '\0' | wc -c)
printf '%s: %d files here, %d in the tree\n' "$dir" "$here" "$tree"

tree was not installed, so no tree output is shown rather than described from memory.

More on ls, find and file sizes

Photo of author
Sudhir P. founded HeatWare.com in 1999 and has built and operated it full-stack ever since; it is now used by more than 88,000 people. He writes here about the PostgreSQL, MySQL, Linux and DevOps work that keeps it running. Articles are rewritten only after the commands in them have actually been run, and the verification scripts are published alongside them so anyone can check the claims. Reach him at blog@heatware.net.