76

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?

0

1 Answer 1

102

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.

7
  • 2
    The result of this query is incomplete for users lacking privileges on the directories that contain the hard links. Commented Jan 16, 2018 at 6:55
  • 8
    Of course. You're listing entries in directories. You need read access to those directories in order to list them. Commented Jan 30, 2018 at 17:01
  • 1
    What could be a reason for the following behaviour? ls -al shows var/www/html/logs to have 4 links to it. I run find / -samefile /var/www/html/logs as user root and it shows me only one entry, not 4... what gives? Commented Nov 9, 2021 at 18:55
  • @pgr As counted by ls -al, every directory has a minimum of two links: itself and .. In addition, if it has subdirectories, then every subdirectory has a file .. that is a hard link back to its parent directory. Thus, according to ls -al, a directory with two subdirectories has a total of four hard links. By contrast, find / -samefile does not include the . and .. directories in its count. Commented Nov 10, 2021 at 22:11
  • @pgr I just this documented online and updated the answer to include the information. Thanks for mentioning this! Commented Nov 10, 2021 at 22:25

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.