May I add some more?
Reasons to use find instead of ls
As stated by mogsie the main reason is about performance:
- ls has no options but sorting (default by name), so it must wait for the whole list to be returned by the OS, and then sort it, before printing it in the standard output
- find, on the other hand, has no sorting capabilities, so nodes are evaluated directly when the OS returns the buffer of nodes, potentially before getting the whole list, and does not need to sort them.
Effective solution
disclosure: I used this solution in production to count entries of a directory with about 300k items
find . -mindepth 1 -maxdepth 1 -printf '.' | wc -m
Basically this prints a dot in the standard output for every fs-entry, then counts the printed characters.
The big advantage on file names is easy to imagine: they are never used; and the other advantage on performance is that no attribute is required to count the files (as you woulod expect from a function that count files in a directory), unless you specify some filter.
If you want to make it start counting and then eventually get back and see how many items have been found, you can also redirect the standard output to a file (eventually in a tmpfs, so you never have to write on disk), then detach the shell and eventually get back and count the characters in the file:
nohup find . -mindepth 1 -maxdepth 1 -printf '.' > /tmp/count.txt &
Then simply counting the dots in the file will give you the current count
wc -m /tmp/count.txt
... and if you are eager to get the current counter's updates
watch wc -m /tmp/count.txt