3

How do I find if any files among two or more directories are hard linked? In other words, do any files under two or more directories refer to the same file?

Similar to How to find all hard links to a given file? [duplicate] and List all files with the same inode number?. However, I'm wondering how to search for any hardlinked files among different directories.

2 Answers 2

5

You can use find to list the inode number of all files in the directories that have more than 1 link, then sort the result and extract the lines where the same inode appears more than once.

The directories should be on the same filesystem:

find dir1 dir2 ... -xdev -type f -links +1 -printf '%i %p\n' |
sort -n -k1,1 |
awk '{   same = ($1==last)
         if(!same)save = $0
         else{ if(save!=""){ print save; save = "" }
                print 
         }
         last = $1
}'

This code prints the files and their inode.

108743 /tmp/a1
108743 /tmp/a2-hardlink-to-a1

If find is not available then use ls -i1.

1

This find command should print all files under directory ./b that link to files under directory ./a.

find ./a -type f -exec find ./b -samefile {} -printf "%p hard link to {}" \;

An example, given file paths and inode numbers

$ find -type f -printf '%p:%i\n' | sort | column -t -s:
./a/f  12977541
./b/f  12977577  # unique file
./c/f  12977541  # points to same file as path ./a/f
#file  inode

Run the find command against directory ./a and ./b to find any hardlinked files under directory ./c.

 $ find ./a ./b -type f -exec find ./c -samefile {} -printf "%p hard link to {}" \;
 ./c/f hard link to ./a/f


This is an O(n^2) operation. It will will take a very long time given a large number of files!

Using GNU find 4.4.2, linux 3.13.0-85, Ubuntu 14.04.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .