How to find all hard links to a given file?

How can we find all hard links to a given file?
I.e., find all other hard links to the same file, given a hard link?

Does filesystem keep track of the hard links to a file?

The inode of a file only stores the number of hard links to the file, but not the hard links, right?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

If the given file is called /path/to/file and you want to find all hard links to it that exist under the current directory, then use:

find . -samefile /path/to/file

The above was tested on GNU find. Although -samefile is not POSIX, it is also supported by Mac OSX find and FreeBSD find.

Documentation

From GNU man find:

-samefile name
       File refers to the same inode as name. When -L is in effect, this can include symbolic links.

Differences between find and ls

ls -l lists the number of hard links to a file or directory. For directories, this number is larger than the number of results shown by find . -samefile. The reason for this is explained in the GNU find manual:

A directory normally has at least two hard links: the entry named in
its parent directory, and the . entry inside of the directory. If a
directory has subdirectories, each of those also has a hard link
called .. to its parent directory.

The . and .. directory entries are not normally searched unless they
are mentioned on the find command line.

In sum, ls -l counts the . and .. directories as separate hard links but find . -samefile does not.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x