Tob*_*ler 36 directory symlink
符号链接到目录会产生不同的结果,ls -l
具体取决于 Iln -s dir
或ln -s dir/
. 但实际的区别是什么,为什么我应该更喜欢哪一个?
小智 28
我唯一能想到的是,它“保护”您免于有人删除目录并创建文件。
[user@host linktest]$ mkdir test
[user@host linktest]$ ln -s test/ slash
[user@host linktest]$ ln -s test noslash
[user@host linktest]$ ls -l
total 4
lrwxrwxrwx 1 paul paul 4 Feb 21 21:00 noslash -> test
lrwxrwxrwx 1 paul paul 5 Feb 21 21:00 slash -> test/
drwxrwxr-x 2 paul paul 4096 Feb 21 20:59 test
[user@host linktest]$ file *slash
noslash: symbolic link to `test'
slash: symbolic link to `test/'
[user@host linktest]$ rmdir test
[user@host linktest]$ file *slash
noslash: broken symbolic link to `test'
slash: broken symbolic link to `test/'
[user@host linktest]$ touch test
[user@host linktest]$ file *slash
noslash: symbolic link to `test'
slash: broken symbolic link to `test/'
[user@host linktest]$
Run Code Online (Sandbox Code Playgroud)
当目标被文件替换时,带斜杠的版本会中断。
有趣的问题。我做了一个小测试:
$ mkdir dir
$ ln -s dir/ test_slash
$ ln -s dir test_noslash
$ ls -l
total 4
drwxr-xr-x 2 vrusinov vrusinov 4096 Feb 21 16:41 dir
lrwxrwxrwx 1 vrusinov vrusinov 3 Feb 21 16:41 test_noslash -> dir
lrwxrwxrwx 1 vrusinov vrusinov 4 Feb 21 16:41 test_slash -> dir/
$ strace ls test_slash 2> trace_slash
$ strace ls test_noslash 2> trace_noslash
$ wc -l trace_*
79 trace_noslash
79 trace_slash
$ diff -u trace_* | less
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,系统调用数量没有差异(至少对于 ls 而言),并且跟踪看起来非常相似。然而,这只是转储测试,我不确定 - 可能存在一些差异。
小智 5
您的问题实际上与ls
程序的行为有关。
1) 如果你ls -l $dir
在 $dir 实际上是一个符号链接的地方做,你会得到关于符号链接的信息。
2) 如果你ls -lL $dir
在 $dir 是一个目录的符号链接的地方做,你会得到关于目标目录的信息。
3) 如果你这样做,ls -l $dir/.
它会强制遵循符号链接并提供有关目标目录的信息。
4) 如果这样做ls -l $dir/
,结果可能与#1 相同,也可能与#3 相同,具体取决于ls
所使用的版本。我习惯了旧版本的 Solaris 像 #1 那样做,而 Linux 像 #3 那样做让我感到惊讶。
为什么我更喜欢哪一个?
如果您可能担心给定的目录名称是实际目录还是指向目录的符号链接,则不要使用斜杠。
如果您更关心目录中的文件而不是目录本身,则使用尾部斜杠。