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
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
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
With GNU find(1) version 4.2.11 or newer you can also use this:
if [ yes = "$(find fileA -prune -samefile fileB -printf yes)" ]; then
echo yes
else
echo no
fi
If fileA is the same file as fileB then find will print "yes" and the condition becomes true.
In contrast to using the file equality operator -ef this will spawn a new process.
You can do this very simply with the built-in bash operator -ef:
[[ file1 -ef file2 ]] && echo Same
If the condition evaluates to true (file1 and file2 are the same), then it prints "Same". Otherwise, nothing is output.
theres is other solution in the sh shell :
#!/bin/sh
file1='readlink $1'
file2='readlink $2'
if [ file1==file2 -o file2==file1 ]
then
echo "the files are linked with strong link"
else
echo "the files are not linked"
fi
the readlink give us the right to copy the inode into a string variable and compare it with other string variable . (two files have a string link have the same inode).