Search code examples
linuxdirectoryhardlink

Hard Links for Directories in Ubuntu


As per my understanding, directories in Linux do not have more than 1 hard links associated with them.

I am running a WSL Ubuntu in Windows, and if I type command ll command in one of the directories, I can see that one of the sub- directory has 5 hard links associated with it.

drwxr-xr-x 5 userK userK  4096 Feb 16 14:15 metastore_db/

In fact, a lot of directories have more than 1 hard links:

userK@C11-J21P22A8R0I:~/spark-3.5.0-bin-hadoop3$ ll
drwxr-xr-x 14 userK userK  4096 Feb  9 09:27 ./
drwxr-x--- 24 userK userK  4096 Feb 19 22:27 ../
-rw-r--r--  1 userK userK 22916 Sep  9 04:08 LICENSE
-rw-r--r--  1 userK userK 57842 Sep  9 04:08 NOTICE
drwxr-xr-x  4 userK userK  4096 Sep  9 04:08 kubernetes/
drwxr-xr-x  2 userK userK  4096 Sep  9 04:08 licenses/
drwxr-xr-x  9 userK userK  4096 Sep  9 04:08 python/
drwxr-xr-x  2 userK userK  4096 Sep  9 04:08 sbin/
drwxr-xr-x  2 userK userK  4096 Sep  9 04:08 yarn/

Why these directories have more than 1 hard link?


Solution

  • The number of hard links for a directory can more than 2 if the directory has sub-directories. Each sub-directory adds an additional hard link to the parent directory.

    parent/
    └── dir
        ├── sub1
        ├── sub2
        └── sub3
    
    5 directories, 0 files
    
    ls -ld parent/dir
    drwxr-xr-x 5 user user 4096 Feb 21 20:26 parent/dir
    

    Here, dir has a link count of 5: the dir entry in /parent, the . entry in /parent/dir, and the .. entry in each of /parent/dir/sub1, /parent/dir/sub2, and /parent/dir/sub3.