Are two files hardlinked?

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 -ef.

[ 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.


function is-hardlinked() {
    r=yes
    [ "`stat -c '%i' $1`" != "`stat -c '%i' $2`" ] && r=no
    echo $r
}

As the first poster suggest, you can write a script based on something like this on Linux:

stat -c '%i' fileA fileB fileC

Tags:

Shell

Files