Linux – Recursively find files with specific hard link count

findhardlinklinux

I have a "tracking" directory containing hardlinks to files/dirs in a second directory ( used for tracking moves/renames). If I delete something in the original folder, no disk space is freed as its hardlink still exists. So I want to clean up this "tracking" directory periodically. Therefore I need to find all files in it, that have a hardlink count of 1.

What is the fastest way to find (and remove) recursively all files with a hardlink count of 1?

I know I can do something like find . -type f -exec ls -l {} \+ | grep -P "^.{11}1" and then some more piping/regexing, but this is ugly and slow. I am looking for something cleaner and faster.

Best Answer

My find has -links option (I'm on Ubuntu 14.04.5 LTS). To find files that have no other hardlinks use:

find -type f -links 1

The command to remove these files is:

find -type f -links 1 -exec rm -f {} +