Ubuntu – How to count the total number of files/folders on a system

command linefilesfilesystemsearch

How can I count the number of all files/folders that exist on a system, using the command-line?

I can find it out using a GUI, simply by opening the properties window for the entire / folder, but it would be nice to know how to do it using the command-line.

Would I need a whole series of commands, or will just one be possible?

Best Answer

Since file / folder names can contain newlines:

sudo find / -type f -printf '.' | wc -c
sudo find / -type d -printf '.' | wc -c

This will count any file / folder in the current / directory. But as muru points out you might want to exclude virtual / other filesystems from the count (the following will exclude any other mounted filesystem):

find / -xdev -type f -printf '.' | wc -c
find / -xdev -type d -printf '.' | wc -c
  • sudo find / -type f -printf '.': prints a dot for each file in /;
  • sudo find / -type d -printf '.': prints a dot for each folder in /;
  • wc -c: counts the number of characters.

Here's an example of how not taking care of newlines in file / folder names may break other methods such as e.g. find / -type f | wc -l and how using find / -type f -printf '.' | wc -c actually makes it right:

% ls
% touch "file
\`dquote> with newline"
% find . -type f | wc -l
2
% find . -type f -printf '.' | wc -c
1

If STDOUT is not a terminal, find will print each file / folder name literally; this means that a file / folder name containing a newline will be printed across two different lines, and that wc -l will count two lines for a single file / folder, ultimately printing a result off by one.