Best Way to Count the Number of Files in a Directory

directoryfileslsshellwildcards

If parsing the output of ls is dangerous because it can break on some funky characters (spaces, \n, … ), what's the best way to know the number of files in a directory?

I usualy rely on find to avoid this parsing, but similarly, find mydir | wc -l will break for the same reasons.

I'm working on Solaris right now, but I'm looking for a answer as portable across different unices and different shells as possible.

Best Answer

How about this trick?

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

As portable as find and wc.

Related Question