Say I just create directory newDirectory and then I do ls -ld command. I see that the number of hard links is 2. What exactly makes the hard link 2 from the start? Also is the number of subdirectories in the current directory equal to the number of hard links - 2?
Historically, the first Unix filesystem created two entries in every directory:
. pointing to the directory itself, and
.. pointing to its parent. This provided an easy way to traverse the filesystem, both for applications and for the OS itself.
Thus each directory has a link count of 2+n where n is the number of subdirectories. The links are the entry for that directory in its parent, the directory's own
. entry, and the
.. entry in each subdirectory. For example, suppose this is the content of the subtree rooted at
/parent, all directories:
/parent /parent/dir /parent/dir/sub1 /parent/dir/sub2 /parent/dir/sub3
dir has a link count of 5: the
dir entry in
. entry in
/parent/dir, and the three
.. entries in each of
/parent/dir/sub1 has no subdirectory, its link count is 2 (the
sub1 entry in
/parent/dir and the
. entry in
To minimize the amount of special-casing for the root directory, which doesn't have a “proper” parent, the root directory contains a
.. entry pointing to itself. This way it, too, has a link count of 2 plus the number of subdirectories, the 2 being
Later filesystems have tended to keep track of parent directories in memory and usually don't need
.. to exist as actual entries; typical modern unix systems treat
.. as special values as part of the filesystem-type-independent filesystem code. Some filesystems still include
.. entries, or pretend to even though nothing appears on the disk.
Most filesystems still report a link count of 2+n for directories regardless of whether
.. entries exist, but there are exceptions, for example btrfs doesn't do this.
There's one for the directory itself, and one for
. inside it.
Also is the number of subdirectories in the current directory equal to the number of hard links - 2?
That makes sense, since each subdirectory creates a
.. hardlink, and beyond that you can't create hardlinks to directories.1 However, I would't trust this for anything serious, esp. since it is easy to count the subdirectories and get the real number.
If you are just looking at
ls output for an idea of how many subs there are, then it does give you a decent idea.
1 Or at least, you can't with
ln. I have not tried to programmatically, and
man 2 link is ambiguous -- there's no obvious error for linking to a directory, although there are a couple that might apply (
EPERM). So unless there's some standard somewhere that says the only possible hard links to a directory are
.., again, I would only treat that hard link count as a casual clue.