Search code examples
bashfindls

Counting total files in directory - find vs ls


Is there a reason why

find . -mindepth 1 -maxdepth 1 | wc -l

is suggested against

ls -1 | wc -l

(or vice-versa ?)

to count the total number of files/directories inside a folder

Notes:

  1. This question is more concerned with just counting stuff.
  2. There are no files with leading .
  3. There may be non-standard files with say a \n in it.

Solution

  • The first command...

    find . -mindepth 1 -maxdepth 1 | wc -l
    

    ...will list files and directories that start with ., while your ls command will not. The equivalent ls command would be:

    ls -A | wc -l
    

    Both will give you the same answers. As folks pointed out in the comments, both of these will give you wrong answers if there are entries that contained embedded newlines, because the above commands are simply counting the number of lines of output.

    Here's one way to count the number of files that is independent of filename quirks:

    find . -mindepth 1 -maxdepth 1 -print0 | xargs -0i echo | wc -l
    

    This passes the filenames to xargs with a NUL terminator, rather than relying on newlines, and then xargs simply prints a blank line for each file, and we count the number of lines of output from xargs.