Directory size is not worth our effort

This is a completely useless, unnecessary in practical application, but a funny little post about directories in *nix systems. It's Friday.

At interviews, boring questions about inodes, everything-is-files, which few people can sanely answer, often slip through. But if you dig a little deeper, you can find interesting things.

To understand the post, a few theses:

  • everything is a file. directory is also a file
  • the inode stores metadata from the file, but the file name is not stored there
  • the filename is stored in the directory data
  • the size of the directory, the one that is shown in ls and is 4Kb by default, depends on the number of files in the directory and the length of their names
  • obviously, the more files, the larger the directory size

And now the interesting part: we create a directory with a million files, check the size of the directory, and then wipe all the files and look at the size of the directory.

$ mkdir niceDir && cd niceDir
# Π² зависимости ΠΎΡ‚ скорости носитСля, ΡΠ»Π΅Π΄ΡƒΡŽΡ‰Π°Ρ ΠΊΠΎΠΌΠ°Π½Π΄Π° ΠΌΠΎΠΆΠ΅Ρ‚ Π·Π°Π½ΡΡ‚ΡŒ 2-10 ΠΌΠΈΠ½ΡƒΡ‚
$ for ((i=1;i<133700;i++)); do touch long_long_looong_man_sakeru_$i ; done
$ ls -lhd .
drwxr-xr-x 2 user user 8.1M Aug 2 13:37 .
$ find . -type f -delete
$ ls -l
total 0
$ ls -lhd .
drwxr-xr-x 2 user user 8.1M Aug  2 13:37 .

As you can see, the size of the directory has not changed, although it would seem πŸ™‚

Repairing the size of a directory (without deleting it) can only be done with fsck (and the -D option) in an unmounted state.

But when I went to look for why this is so, it turned out that 10 years ago this behavior was already discussed in lkml. And according to the developers, the fix is ​​simply not worth the effort.

Source: habr.com

Add a comment