Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Count Files in a Linux Directory Quickly

1 min read .
Count Files in a Linux Directory Quickly

Counting files is useful in shell scripts, backups, log maintenance, migration checks, and filesystem monitoring. The right command depends on whether you want only regular files, recursive results, hidden files, directories, or symbolic links.

Count Regular Files in One Directory

With GNU find:

find /path/to/directory -maxdepth 1 -type f -printf '.' | wc -c

-maxdepth 1 prevents recursion into subdirectories. Hidden files are included automatically.

A simpler command often seen online is:

ls -1 /path/to/directory | wc -l

but it counts directory entries rather than only regular files, omits hidden names by default, and parsing ls is not ideal for scripts.

Count Files Recursively

find /path/to/directory -type f -printf '.' | wc -c

For portable scripts on systems whose find does not support -printf, this is common:

find /path/to/directory -type f | wc -l

Be aware that filenames containing newlines can make line-counting approaches inaccurate.

Count Files by Name Pattern

find /path/to/directory -type f -name '*.txt' -printf '.' | wc -c

For case-insensitive matching with GNU find:

find /path/to/directory -type f -iname '*.txt' -printf '.' | wc -c
find /path/to/directory -type d -printf '.' | wc -c
find /path/to/directory -type l -printf '.' | wc -c

The directory count includes the starting directory itself unless you add -mindepth 1.

Put It in a Script

#!/usr/bin/env bash
set -euo pipefail

directory=${1:?"usage: $0 DIRECTORY"}
count=$(find "$directory" -type f -printf '.' | wc -c)
printf '%s files in %s\n' "$count" "$directory"

Always quote path variables so spaces and wildcard characters are handled correctly.

Conclusion

Use find when you need a precise file type and recursion rule. ls | wc can be convenient for interactive inspection, but find is usually the better foundation for automation.

Related Posts

chevron-up