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

417 Views Asked by At

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?

1

There are 1 best solutions below

0
knittl On BEST ANSWER

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:

  • b (from the parent directory)
  • . (from the directory itself)
  • c/..
  • d/..

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:

  • a: 3
    • a (from /)
    • .
    • b/..
  • c: 2
    • c (from b)
    • .
  • d: 2
    • d (from b)
    • .