How can I find the number of files on a filesystem?
Solution 1
The --inodes option to df
will tell you how many inodes are reserved for use. For example:
$ df --inodes / /home
Filesystem Inodes IUsed IFree IUse% Mounted on
/dev/sda1 3981312 641704 3339608 17% /
/dev/sda8 30588928 332207 30256721 2% /home
$ sudo find / -xdev -print | wc -l
642070
$ sudo find /home -print | wc -l
332158
$ sudo find /home -type f -print | wc -l
284204
Notice that the number of entries returned from find
is greater than IUsed
for the root (/) filesystem, but is less for /home. But both are within 0.0005%. The reason for the discrepancies is because of hard links and similar situations.
Remember that directories, symlinks, UNIX domain sockets and named pipes are all 'files' as it relates to the filesystem. So using find -type f
flag is wildly inaccurate, from a statistical viewpoint.
Solution 2
Use statvfs()
, and calculate f_files - f_ffree
.
Related videos on Youtube
zilitron
I write lots of code for fun and pay. Go, Rust, and Javascript are my specialties, though I'm confident in Python, Java, C#, C++, and C, with passing interest in a few other languages.
Updated on September 18, 2022Comments
-
zilitron over 1 year
I want to know how many files I have on my filesystem. I know I can do something like this:
find / -type f | wc -l
This seems highly inefficient. What I'd really like is to do is find the total number of unique inodes that are considered a 'file'.
Is there a better way?
Note:
I would like to do this because I am developing a file synchronization program, and I would like to do some statistical analysis (like how many files the average user has total vs how many files are on the system). I don't, however, need to know anything about those files, just that they exist (paths don't matter at all). I would especially like to know this info for each mounted filesystem (and it's associated mount point).
-
zilitron over 12 yearsI think this is what I'm looking for. Is there any way to find out how many of each type of file there is? This isn't directly needed by my application, but could be useful knowledge.
-
Arcege over 12 yearsNot without inspecting the inodes of each file in the filesystem, which would be about the same as doing the find.
-
zilitron over 12 yearsDoes df understand most filesystems (ext2-4, ntfs, fat, reiserfs, etc)?
-
Arcege over 12 yearsIt would understand any filesystem type that could be mounted. Some filesystem types do not have inodes (for example, fat);
df
would display the total number of inodes as 0 on those filesystems. Other types should show the underlying filesystem's inode stats. -
n0pe over 12 yearsWould you have to redirect errors to
/dev/null
seeing as you would get lines warning you that files in/proc
are "virtual"? -
Arcege over 12 yearsThe
-xdev
option in find would prevent traversing into the /proc and /sys filesystems. With thesudo
, the commands have enough read access to directories and inodes to not generate errors.