The number of links for a folder doesn't reflect the real status?

A question for ls command.

root@cqcloud script]# ls /var/www/html -la 
total 36 
drwxr-xr-x  9 root root 4096 Aug 31 01:12 .
drwxr-xr-x  7 root root 4096 Aug 31 01:10 ..
drwxr-xr-x  2 root root 4096 Aug 26 04:07 cmd
drwxr-xr-x  5 root root 4096 Jul  3 10:07 cn.fnmili.com
drwxr-xr-x  7 root root 4096 Aug 30 11:42 internal
drwxr-xr-x  3 root root 4096 Jul 25 02:03 node
drwxr-xr-x  4 root root 4096 Jul 11 01:26 sandbox
drwxr-xr-x 13 root root 4096 Aug 26 03:45 tpshop
drwxr-xr-x  2 root root 4096 Aug 31 01:12 trash

[root@cqcloud script]# ls /var/www/html/cmd -la 
total 16 
drwxr-xr-x 2 root root 4096 Aug 26 04:07 . 
drwxr-xr-x 9 root root 4096 Aug 31 01:12 .. 
-rw-r--r-- 1 root root 52 Aug 26 04:07 .htaccess 
-rw-r--r-- 1 root root 73 Aug 26 04:02 df.php

You can see that the cmd folder has a link count of 2, but it actually has 4 links, including 2 files, . and .. folder. Can anyone explain why?

Asked By: Weijing Lin

||

The link count for a directory is the number of names that directory has (this works just as for regular files).

Your cmd directory has two names:

  1. cmd in its parent directory.
  2. . in the directory itself.

The /var/www/html directory has nine names:

  1. html in its parent directory.
  2. . in itself.
  3. .. in each of its (seven) subdirectories.

Under normal circumstances, the link count for a directory’s . entry should be 2 plus the number of subdirectories that it contains.


This is also true for the root directory /, even though it does not have a parent directory and therefore ought to have a link count of 1 plus the number of subdirectories.

What it does have is a .. directory, which takes you back to /. So that solves that riddle; it’s /.. that provides the “extra” link to /. This is the only directory whose .. directory is a link back to ..

Answered By: Kusalananda
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.