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.
find
will get you number of files recursively (use-maxdepth 1
if you don't want that.find mydir -maxdepth 1 -type f -printf \\n | wc -l
should handle the special characters in the filename, as they are never printed in the first place. – Anthon May 06 '15 at 06:20