When you view a file or directory in Linux with the long listing of ls, ls -l or perhaps using the command stat we can see the number of hard links to the file or directory; if using stat we can choose to output only the number of hard links with:
stat -c %h /usr/share/doc
Output of ls -l
Output from stat against the same directory
For a directory this value will always be a minimum of 2; the actual name and the directory and each directory has a link called . that points to itself. The directory . meaning this directory. Additionally to the hard link . each directory has a link .. , meaning the parent directory. In this way we can use the command
to change to the parent directory.
Using cd .. to change to the parent directory
If each sub-directory then has a link to the parent directory we can easily calculate the number of sub-directories and given directory has.
- If the link count is 2 the directory has no sub-directories
- For each sub-directory that exists there will be a corresponding hard link .. that points to the parent directory
- So we can calculate the sub-directory count as SUBDIRS=LINKCOUNT-2
Using a script to count sub-directories
The video that follows will guide you through the demo 🙂