4

I have a directory with lots of files.

How can I find out by the size of meta data reported by ls

drwxr-x--- 2 www-data www-data 1017M Aug  8 10:44 cookies_

How many files are in the directory.

I do not want to count them (even in Determining number of files in a directory without counting them there are counting them)

Alex
  • 436
  • 1
  • 4
  • 13

1 Answers1

17

You can’t, for a number of reasons.

The first is that a directory’s size grows, but it doesn’t shrink (on most file systems anyway). Try this:

mkdir testdir && cd testdir
touch {1..100000}
rm {1..100000}
ls -ld ../testdir

This will produce a fairly large directory (nothing like yours admittedly, but that’s irrelevant here) containing no files...

The second is that in most cases, file records inside a directory entry are variable in length, depending on the file’s name. See for example the ext4 disk layout.

The third is that the directory might not even be linear, which complicates matters further.

The fourth is that a directory’s size is a multiple of the block size, so a directory with one file and a directory with twenty will usually have the same size.

Stephen Kitt
  • 434,908
  • Can the second and third reason be mitigated if you know approximately the size of the filename, and the structure of the directory? (Not sure what you mean by linear here) – pipe Aug 08 '17 at 11:27
  • @pipe if all the files have names with similar lengths, you can use that to get an approximate upper bound to the number of files in the directory — if your file names occupy 12 bytes on average, an ext4 directory will use 20 bytes on average per entry (plus checksum blocks). By non-linear, I mean that there might be holes (in some file systems), or even tree structures. – Stephen Kitt Aug 08 '17 at 11:35