How can I tell if two files are hard-linked from the command line? e.g. something link this:
$ ls fileA fileB fileC $ is-hardlinked fileA fileB yes $ is-hardlinked fileA fileC no
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.Sign up to join this community
On most filesystems¹, a file is uniquely determined by its inode number, so all you need to check is whether the two files have the same inode number and are on the same filesystem.
Ash, ksh, bash and zsh have a construct that does the check for you: the file equality operator
[ fileA -ef fileB ] && ! [ fileA -ef fileC ]
For more advanced cases,
ls -i /path/to/file lists a file's inode number.
df -P /path/to/file shows what filesystem the file is on (if two files are in the same directory, they're on the same filesystem). If your system has the
stat command, it can probably show the inode and filesystem numbers (
stat varies from system to system, check your documentation). If you want a quick glance of hard links inside a directory, try
ls -i | sort (possibly piped to awk).
¹ All native unix filesystems, and a few others such as NTFS, but possibly not exotic cases like CramFS.
find(1) version 4.2.11 or newer you can also use this:
if [ "yes" = "$(find fileA -samefile fileB -exec echo yes \;)" ]; then echo yes else echo no fi
fileA is the same file as
find will print "yes" and the condition becomes true.
In contrast to using the file equality operator
-ef this will spawn a new process.