删除所有用行断开的符号链接?
对于给定的文件夹,如何删除其中的所有断开链接?
For a given folder, how can I delete all broken links within it?
我找到了此答案,其中显示了如何删除一个断开的链接,但是我不能只在一行中放在一起.有单线吗?
I found this answer that shows how to delete one broken link, but I can't put that together in only one line. Is there a one-liner for this?
损坏的符号是指向不再存在的文件/文件夹的链接.
A broken symbolic is a link that points to a file/folder that doesn't exists any longer.
这是一种POSIX方式,无需递归即可删除当前目录中所有损坏的符号链接.它通过告诉 find
遍历符号链接( -L
),但在每个目录或符号链接处停止( -prune
)来工作到这样.
Here's a POSIX way of deleting all broken symbolic links in the current directory, without recursion. It works by telling find
to traverse symbolic links (-L
), but stopping (-prune
) at every directory-or-symbolic-link-to-such.
find -L . -name . -o -type d -prune -o -type l -exec rm {} +
您也可以使用Shell循环.测试 -L
匹配符号链接,而 -e
匹配现有文件(不包括损坏的符号链接).
You can also use a shell loop. The test -L
matches symbolic links, and -e
matches existing files (excluding broken symlinks).
for x in * .[!.]* ..?*; do if [ -L "$x" ] && ! [ -e "$x" ]; then rm -- "$x"; fi; done
如果要递归到子目录,此技术将不起作用.使用GNU find(在非嵌入式Linux和Cygwin上可以找到),您可以使用 -xtype
谓词来检测断开的符号链接( -xtype
使用目标的类型表示符号链接,并报告 l
断开的链接).
If you want to recurse into subdirectories, this technique doesn't work. With GNU find (as found on non-embedded Linux and Cygwin), you can use the -xtype
predicate to detect broken symbolic links (-xtype
uses the type of the target for symbolic links, and reports l
for broken links).
find -xtype l -delete
POSIXly,您需要组合两个工具.您可以使用 find -type l -exec…
在每个符号链接上调用命令,并使用 [-e"$ x"]
测试该链接是否为非-坏了.
POSIXly, you need to combine two tools. You can use find -type l -exec …
to invoke a command on each symbolic link, and [ -e "$x" ]
to test whether that link is non-broken.
find . -type l -exec sh -c 'for x; do [ -e "$x" ] || rm "$x"; done' _ {} +
最简单的解决方案是使用zsh.要删除当前目录中所有断开的符号链接,请执行以下操作:
The simplest solution is to use zsh. To delete all broken symbolic links in the current directory:
rm -- *(-@D)
括号中的字符为 glob限定符:-
取消引用符号链接, @
仅匹配符号链接(组合-@@
仅意味着断开的符号链接),而 D
取消引用匹配点文件.要递归到子目录,请执行以下操作:
The characters in parentheses are glob qualifiers: -
to dereference symlinks, @
to match only symlinks (the combination -@
means broken symlinks only), and D
to match dot files. To recurse into subdirectories, make that:
rm -- **/*(-@D)