Counting and listing hard links on Linux

A hard link is actually nothing more than a regular directory entry, which in turn can be seen as a pointer to the actual file’s data on the disk. The cool thing about hard-links is that a file can be stored once on the disk, and be linked to multiple times, from different locations/entries, without requiring to allocate extra disk space for each file instance.

But then a question arises: Given a specific file on disk, how can someone know whether it is linked to by other directory entries or not? This can be easily answered using the ls command:

[email protected]:/etc$ ls -l passwd
-rw-r–r– 1 root root 1402 2008-03-30 17:49 passwd;

Do you ever wonder what is this small number between the file permissions and the owner in the output of ls???s long listing format (its value is usually ???1??? for files, or ???2??? for directories)? This number is actually the link-count of the file, when referring to a file, or the number of contained directory entries, when referring to a directory (including the . and .. entries).