1

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.

3

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. Obviously, the directories have to be on the same filesystem:

find dir1 dir2 ... -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. For people without find -printf, use -ls which prints a bit more but will do.

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.