如何查找当前目录下的所有软链接(符号链接)?

bgu*_*uiz 10 bash symbolic-link ls ln shell-script

问题与 .shell 脚本有关bash

如何使用脚本检查当前目录中的哪些文件是软链接?

如果我使用了错误的术语,当我说soft links 时,我指的是使用ln -s.

我唯一能想到的是ls -la作为一个表达式进行评估,并解析它的结果,但这显然不是最好的解决方案。

Pol*_*lsy 14

请参阅“条件表达式”man bash-你想这种情况下-h

for file in *
do
  if [ -h "$file" ]; then
    echo "$file"
  fi
done
Run Code Online (Sandbox Code Playgroud)

  • http://www.faqs.org/docs/bashman/bashref_68.html - 条件表达式比手册页更容易阅读。 (2认同)

Arj*_*jan 14

您可能并不真正需要脚本。要仅在当前文件夹中显示任何符号链接,而不递归到任何子文件夹中:

找 。-maxdepth 1 -type l -print

或者,要获取更多信息,请使用以下方法之一:

找 。-maxdepth 1 -type l -exec ls -ld {} +
找 。-maxdepth 1 -type l -print0 | xargs -0 ls -ld

要知道,如果一个文件是一个符号链接,可以使用readlink,这将输出什么,如果它不是一个符号链接。以下示例不是很有用,但显示了如何readlink忽略普通文件和文件夹。使用以下之一:

找 。-maxdepth 1 -exec readlink {} +
找 。-maxdepth 1 -print0 | xargs -0 阅读链接

请注意,上面的-exec ... +xargs ...-exec ... \;. 喜欢:

时间 find /usr/bin -maxdepth 1 -type l -exec ls -ld {} \;
真实 0m0.372s
用户 0m0.087s
系统 0m0.163s

时间查找 /usr/bin -maxdepth 1 -type l -exec ls -ld {} +
真实 0m0.013s
用户 0m0.004s
系统 0m0.008s

时间 find /usr/bin -maxdepth 1 -type l -print0 | xargs -0 ls -ld
真实 0m0.012s
用户 0m0.004s
系统 0m0.009s