mkdir d
mkdir d/a
mkdir d/b
mkdir d/c
While executing these commands in terminal, what would be the link count of the directory d?
On POSIX systems, You can use the stat()
syscall to read st_nlink
to get the number of hard links of any file or directory, per what the filesystem containing it defines as "number of hard links"
But POSIX doesn't actually define what "number of hard links" to a directory means. Directories cannot have hard links, so their theoretical hard link count is always 1.
Different filesystems use st_nlink
to relay different information about the directory:
On Linux (ext4), st_nlink
means the number of subdirectories of that directory, plus its special entries:
$ ls -F d/
a/ b/ c/ d e f
$ ls -a d/
. .. a b c d e f
$ ls -a d/ | wc -l
8
$ ls -al d/ | grep ^d | wc -l
5
$ stat --printf %h d/
5
So if you run the commands in your questions, you'll get 5.
MacOS (apfs), on the other hand, defines it as the number of all entries in that directory, plus its special entries:
$ ls -F d/
a/ b/ c/ d e f
$ ls -a d/
. .. a b c d e f
$ ls -a d/ | wc -l
8
$ ls -al d/ | grep ^d | wc -l
5
$ stat --printf %h d/ # with GNU coreutils
8
So if you run the commands in your questions, you'll get 8.