用 bash test -ef 比较一个符号链接和他的目标

Compare a symlink and his target with bash test -ef

TL;DR:为什么 [ symlink_to_file_a -ef file_a ] return 正确?


我需要测试文件 b(主要是 symlink)是否与文件 a 相同试图知道 ab 是否很难 link 在一起,如果不是 link 它们案例.
我使用条件表达式 -efbash manual 说:

file1 -ef file2
True if file1 and file2 refer to the same device and inode numbers.

我只比较symlink/regular文件,ab的索引节点不同,但结果是True.

一个类似 question 的回答说:

If yes, then will the inode number be same for target and links?

没有。通常,symlink 是一个有自己 inode 的文件,(有文件类型,自己的数据块等)

我不确定我理解了什么,但我可能会在 ext4 spec 中找到一些解释:

The target of a symbolic link will be stored in this field if the target string is less than 60 bytes long. Otherwise, either extents or block maps will be used to allocate data blocks to store the link target.

我尝试使用目标 shorter/longer 和 60B,但没有区别。

$ cat test.sh
#!/usr/bin/env bash
foo="foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"
mkdir /tmp/test
cd /tmp/test
touch a
ln -s /tmp/test/a b
ls -li
if [ a -ef b ]
then
  echo b : same device or inode of a
 else
  echo b : different device or inode of a
fi
mkdir /tmp/test/${foo}
cd /tmp/test/${foo}
touch c
ln -s /tmp/test/${foo}/c d
ls -li
if [ c -ef d ]
then
  echo d : same device or inode of c
else
  echo d : different device or inode of c
fi
$ ./test.sh
156490 -rw-rw-r-- 1 msi msi  0 nov.  25 23:55 a                                                                                                                                                                                                
156491 lrwxrwxrwx 1 msi msi 11 nov.  25 23:55 b -> /tmp/test/a                                                                                                                                                                                 
b : same device or inode of a                                                                                                                                                                                                                  
total 4                                                                                                                                                                                                                                        
156494 -rw-rw-r-- 1 msi msi   0 nov.  25 23:55 c
156495 lrwxrwxrwx 1 msi msi 155 nov.  25 23:55 d -> /tmp/test/foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo/c
d : same device or inode of c

索引节点不同,但测试成功,但我没看出问题所在。

似乎文档在某些地方具有误导性。来自 http://www.tldp.org/LDP/abs/html/fto.html:

f1 -ef f2

files f1 and f2 are hard links to the same file

您自己已经发现,表达式 returns 不仅适用于硬链接,而且适用于 链接到同一文件。

改用stat

if [ "$(stat -c "%d:%i" FILE1)" == "$(stat -c "%d:%i" FILE2)" ]

来源: https://superuser.com/questions/196572/check-if-two-paths-are-pointing-to-the-same-file