How to find all hard links in a directory on Linux
I
have a file named /etc/passwd i and I would like to find all hard links to this file in a directory. How do I find out all other hard links to the /etc/passwd in /backups/ directory? How can find all hard links to a given file using Linux or Unix command line option?
You can use the find command on Linux, Apple MacOS, FreeBSD and other operating systems to find out all hard links.
How to find all hard links to a given file
A hard link is nothing but the specific location of physical data. You give various names that refer to the same file. File refers to the same inode as name. Hard links to foo file can be created as follows:
$ ln foo bar
$ ln foo dir2/foobar
In above example, bar and foobar become another name of foo file. The syntax is as follows to find all hard links for foo file in current directory:
find /dir/to/search/ -samefile /path/to/file/name
To find out all hard links to foo, use this command:
find / -samefile foo
find / -xdev -samefile foo
Examples
If the file named /etc/passswd and you need to get all hard links to it that exists under /backups/ directory, run:
$ find /backups/ -samefile /etc/passwd
Sample outputs:
/backups/hourly.0/etc/passwd
/backups/hourly.4/etc/passwd
/backups/hourly.3/etc/passwd
/backups/daily.0/etc/passwd
/backups/hourly.1/etc/passwd
/backups/hourly.2/etc/passwd
If you do not want to descend directories on other filesystems such as mounted once, try:
$ find /backups/ -xdev -samefile /etc/passwd
FIND AND DELETE ALL HARD LINKS TO A FILE NAMED FOO IN /TMP/ DIRECTORY
Type the following command:
$ find /tmp/ -xdev -samefile foo -print0 | xargs -I {} -0 rm -v {}
Sample outputs:
removed ‘/tmp/dir2/foobar’
removed ‘/tmp/foo’
removed ‘/tmp/bar’
Help, -samefile option is not supported by my find command
Find find the file’s inode number, enter:
$ ls -li fileNameHere
$ ls -li /tmp/demo.txt
Sample outputs:
4065089 -rw-r–r– 3 vivek vivek 8 Feb 26 02:19 /tmp/demo.txt
The first column in the above output displayes the file’s inode # 4065089. Now the alternate syntax is as follows to find all hard links for a file named /tmp/demo.txt using inode # 4065089:
$ find /tmp/ -inum 4065089
$ find /tmp/ -xdev -inum 4065089
Sample outputs:
/tmp/demo.txt
/tmp/dir2/file2.txt
/tmp/file1.txt
To find and delete all all hard links to a file by an inode number # 4065089, run:
$ find /tmp/ -xdev -inum 4065089 | xargs rm -v
$ find /tmp/ -xdev -inum 4065089 -print0 | xargs -I {} -0 rm -v {}
Here is my sample session:
Fig.01: How to find all hard links to a given file name