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.
ls -al
showsvar/www/html/logs
to have 4 links to it. I runfind / -samefile /var/www/html/logs
as userroot
and it shows me only one entry, not 4... what gives? – pgr Nov 09 '21 at 18:55ls -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 tols -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. – John1024 Nov 10 '21 at 22:11