I want to know the total number of files on my server. Can this be done?
Depending on what exactly you want to count, you are better doing this per filesystem rather than counting all files under root. Counting everything under root would also count
To count everything on the root filesystem using GNU
With a POSIX find you could simply do:
Or POSIXly and avoiding any file containing newlines from being counted twice:
Here each file becomes a different argument to
A simpler (but slower) POSIX solution:
As noted by @Gilles, using
Another point by Gilles was that files with multiple hard links will be counted as different files. This may not be desirable on a filsystem where, for example increment backup trees have been created by hardlinking unchanged files in a newer tree to those in an older one. To overcome this with GNU tools you could do:
Using POSIX tools:
No problems with newlines in filenames here since the
If you want the number of files in a directory tree, then you can use the following command:
Add the option
Another way to count is
or, to cope with file names containing newlines, with GNU find (non-embedded Linux or Cygwin):
This is the fastest method I can imagine that this can be done fully portably. I use
portable and very fast:
I don't believe you do need all of the rest - though @Graeme was correct about the possible misses below. This, however, does not have the same shortcomings:
All you need to do is ensure a full path to root and you don't have to jump through all of the other hoops.
NOTE: As Gilles points out, using -type f is an egregious error. I have updated this post to reflect this.
Also for a more accurate count, you need only do:
Provided your tools are up to date, that will provide you with the exact number of files in your root filesystem. This can be used for any directory as well.
Here's a means of getting an exact count of all files in any filesystem or subdirectory excluding hardlinks with only very commonly available tools. First isolate target root with a
Next, count your files:
I did something very similar to this for another answer a few days ago - though that was a little more complicated because the goal was to sort by subdirectories containing the highest file counts - so the command there looks a little different than the one here. But this is still very fast, by the way.
Anyway, the heart of that is the
From your root directory:
You can change the path (here .) to whatever the directory you want to count the files in.
If you don't want to go in subdirectories, add the option