How to count the total number of files/folders on a system?
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.
1 method would be
sudo find / -type f | wc -l
sudo find / -type d | wc -l
(sudo to prevent accessing errors)
f for files, d for directories.
The /proc/ filesystem will error out but I do not consider those files ;)
If you really want the total number of objects in your filesystems, use df -i
to count inodes. You won't get the breakdown between directories and plain files, but on the plus side it runs near-instantly. The total number of used inodes is something filesystems already track.
If you want to use one of the find
-based suggestions, don't just run it on /
. Use find -xdev
on a list of mount points generated by something like findmnt --list -v -U -t xfs,ext3,ext4,btrfs,vfat,ntfs -o TARGET
or something. That doesn't exclude bind mounts, though, so files under bind mounts will get counted twice. findmnt
is pretty cool.
Also, surely there's a straightforward way to list all your "disk" mounts without having to list explicit filesystem types, but I'm not sure exactly what.
As suggested by another answer, use find -printf . | wc -c
to avoid any possible problems counting funny characters in filenames. Use -not -type d
to count non-directory files. (You don't want to exclude your symlinks, do you?)
sudo find / -type f | wc -l
will tell you the number of regular files on your system, and
sudo find / -type d | wc -l
the number of folders.
Using zsh
:
As root
, for regular files:
files=( /**/*(.D) )
this will take all the regular files including the ones starting with a .
into the array files
, now we can simply count the number of elements of the array:
echo $#files
this will handle all the edge cases e.g. unusual file names.
Similarly for directories:
dirs=( /**/*(/D) )
echo $#dirs