How to find hard links or files that point to a specific file
If you want to know which hard links are present, the find utility can give you the answer. In this article we have a look at a few ways to discover more information about hard links.
Good to know: a hard link shares the same inode, where a symbolic link has its own inode and just points from one to another.
Show all hard links within a specific file system or directory
When we have a directory with hard links, we can discover by looking at the link count of each file. If it has more than 1 link, then there must be a hard link present.
find . -xdev \! -type d -links +1 -printf '%40p --> inode %i\n' | sort
If you want to use this information and parse it in an easier way, change the printf into ’%i=%p\n’.
In the example above we only searched in the current directory and below. You can change this into a specific file system. The -xdev prevents searching on external file systems (e.g. NFS).
Show other files that link to the same inode or file
There are a few ways to use find to also look the related files that link to a specific inode. This is the specific unique pointer stored in a file system. To show the inode, use the \-i
option:
ls -li /etc
The first column listed is the inode.
To see which files are pointing to this inode, we can use the find command and define what inode we are looking for.
find . -inum 123456
Another option is to specify the file name itself. In other words, we ask find to lookup the inode and do the same step as above, but simplified.
find . -samefile /path/to/the/file
If you suspect that there are hard links to the same file outside the current work directory, then provide the full file system.