bashunixcommand-linehardlink

Why is number of hard links for a directory 2 + the number of subdirectories?


When using ls -l, I noticed that directories start with 2 hard links, and gain one for each subdirectory. I understand that the current directory link . counts as one link and the parent directory link .. of each subdirectory counts as a hard link, but:

  1. Why don't subfiles count towards hard links when subdirectories do?

  2. Why does the parent directory link .. count as a hard link for both this directory and the parent directory?


Solution

  • Assume the following directory tree

    /a
      /b
        /c
        /d
    

    Then directory b at path /a/b has 4 hard links. The links are the following:

    Files don't count against the link count of a directory, because files do not have a nested .. directory, thus do not point back to the directory.

    We can calculate the number of hardlinks for each directory shown above: