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:
.
\n
in it.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
.