如何检查文件是否是指向目录的符号链接?

rub*_*o77 93 shell bash test

我可以检查文件是否存在并且是带有 -L 的符号链接

for file in *; do
    if [[ -L "$file" ]]; then echo "$file is a symlink"; else echo "$file is not a symlink"; fi
done
Run Code Online (Sandbox Code Playgroud)

如果它是带有 -d 的目录:

for file in *; do
    if [[ -d "$file" ]]; then echo "$file is a directory"; else echo "$file is a regular file"; fi
done
Run Code Online (Sandbox Code Playgroud)

但是我怎样才能只测试到目录的链接呢?


我模拟了一个测试文件夹中的所有案例:

/tmp/test# ls
a  b  c/  d@  e@  f@

/tmp/test# file *
a: ASCII text
b: ASCII text
c: directory
d: symbolic link to `c'
e: symbolic link to `a'
f: broken symbolic link to `nofile'
Run Code Online (Sandbox Code Playgroud)

小智 105

只需将两个测试与&&

if [[ -L "$file" && -d "$file" ]]
then
    echo "$file is a symlink to a directory"
fi
Run Code Online (Sandbox Code Playgroud)

  • [ -L "$file" ] && [ -d "$file" ] 不是更好吗?一些在 shell 之间具有可移植性的东西 iirc。 (4认同)
  • @Lennart OP 的示例代码使用`[[`,我将其作为逻辑起点。讨论 `[` 与 `[[` 的优点超出了这个答案的范围(但可用 [here](http://stackoverflow.com/q/669452))。 (4认同)

Mar*_*ton 13

这是一个命令,它将递归列出目标是目录(从当前目录开始)的符号链接:

find . -type l -xtype d

参考:http : //www.commandlinefu.com/commands/view/6105/find-all-symlinks-that-link-to-directories