What's the best way to count the number of files in a directory?

How about this trick?

find . -maxdepth 1 -exec echo \; | wc -l

As portable as find and wc.


With bash, without external utilities, nor loops:

shopt -s dotglob
files=(*)
echo ${#files[@]}

In ksh, replace shopt -s dotglob by FIGNORE=.?(.). In zsh, replace it by setopt glob_dots, or remove the shopt call and use files=(*(D)). (Or just drop the line if you don't want to include dot files.) Portably, if you don't care about dot files:

set -- *
echo $#

If you do want to include dot files:

set -- *
if [ -e "$1" ]; then c=$#; else c=0; fi
set .[!.]*
if [ -e "$1" ]; then c=$((c+$#)); fi
set ..?*
if [ -e "$1" ]; then c=$((c+$#)); fi
echo $c

find . ! -name . -prune -print | grep -c /

Should be fairly portable to post-80s systems.

That counts all the directory entries except . and .. in the current directory.

To count files in subdirectories as well:

find .//. ! -name . | grep -c //

(that one should be portable even to Unix V6 (1975), since it doesn't need -prune)