Skip to content
shellhacks.dev
Command Line

Count the files in a directory

Count the files in a directory with ls -A | wc -l, or with find when names may contain newlines. A plain ls -1 skips every hidden file.

1 min read
Summarize in AI

You need the number of entries in one directory, and the obvious command undercounts when dotfiles are present.

Shell
mkdir demo && cd demo
touch a b c .hidden
ls -1 | wc -l
ls -A | wc -l
find . -mindepth 1 -maxdepth 1 | wc -l
touch "$(printf 'two\nlines')"
ls -A | wc -l
find . -mindepth 1 -maxdepth 1 -printf x | wc -c
Text
3
4
4
6
5

ls -1 leaves out names that start with a dot, and -A brings them back without the . and .. entries that -a adds. Counting lines is wrong when a name holds a newline, as the fifth command shows with a file called "two" newline "lines". find -printf x prints one character per entry no matter what the name is, so counting characters is exact. Options are in the GNU find manual.

-printf is a GNU find extension. On BSD use find . -mindepth 1 -maxdepth 1 -exec echo x ';' | wc -l, or accept that newline in names is rare enough in your data to ignore. The count includes directories, not just regular files.

Share

More snippets

Command Line

List hidden files only

List hidden files only with ls -d .[!.]* in GNU coreutils 9 or any POSIX shell. The glob skips the dot and double dot entries that .* would match.

1 min read
Command Line

Show the full timestamp of files

Show the full timestamp of every file with ls -l --full-time in GNU coreutils. It prints nanosecond precision and the zone, which ls -l hides.

1 min read
Command Line

Copy a directory including hidden files

Copy a directory with its dotfiles using cp -a src/. dst/. The usual src/* glob skips hidden files, and the dot form needs no shell option.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.