删除文件夹中的所有符号链接

Nun*_*eca 20 symbolic-link

如何一次删除文件夹中的所有符号链接(数十个)?使用 unlink 或 rm 时,手动插入其中的每一个是不切实际的。

moo*_*765 34

您可以使用find- 命令来执行此操作:

find /path/to/directory -maxdepth 1 -type l -delete
Run Code Online (Sandbox Code Playgroud)

为了安全起见,首先检查不带-delete- 选项:

find /path/to/directory -maxdepth 1 -type l
Run Code Online (Sandbox Code Playgroud)

-maxdepth 1确保find只在其子文件夹中查找/path/to/directory而不是在其子文件夹中查找符号链接。随意看一下man find


sud*_*dus 14

列出当前目录别名文件夹中的链接并检查您是否确实要删除它们,

find -type l -ls                  # search also in subdirectories

find -maxdepth 1 -type l -ls      # search only in the directory itself
Run Code Online (Sandbox Code Playgroud)

如果情况看起来不错,并且您想删除这些链接,请运行

find -type l -delete              # delete also in subdirectories

find -maxdepth 1 -type l -delete  # delete only in the directory itself
Run Code Online (Sandbox Code Playgroud)

如果你想交互式删除,可以使用下面的命令行(这样比较安全)

find -type l -exec rm -i {} +              # delete also in subdirectories

find -maxdepth 1 -type l -exec rm -i {} +  # delete only in the directory itself
Run Code Online (Sandbox Code Playgroud)

  • 使用第一个交互选项,您可能还需要使用“-深度”来确保深度优先遍历 - 也就是说,它在“root/symlink1”之前询问“root/symlink1/symlink2”。 (2认同)

mar*_*elm 10

对于Z shell的用户来说,rm *(@)将会实现这一点。

Zsh 支持glob 限定符,这些限定符限制 glob(例如*)适用的文件类型,例如(/)目录、(x)可执行文件、(L0)空文件和(@)符号链接。

对于符号链接:

% ll
lrwxrwxrwx 1 test test 3 Aug  8 15:51 bar -> foo
-rw-r--r-- 1 test test 0 Aug  8 15:51 baz
-rw-r--r-- 1 test test 0 Aug  8 15:52 foo
lrwxrwxrwx 1 test test 4 Aug  8 15:51 qux -> /etc/ 

% rm *(@)                                                                         
removed 'bar'
removed 'qux'

% ll                                                                              
-rw-r--r-- 1 test test 0 Aug  8 15:51 baz
-rw-r--r-- 1 test test 0 Aug  8 15:52 foo
Run Code Online (Sandbox Code Playgroud)

  • 很好:-)…为了安全起见,在使用“rm”之前先用“echo”进行一次试运行可能是个好主意。 (2认同)

Raf*_*ffa 7

bash和大多数 shell)中 \xe2\x80\xa6 内置命令test及其变体[有一个选项-h或者-L如果它\xe2\x80\x99s更容易记住)将返回成功(exit 0 )符号链接 \xe2\x80\xa6 因此它可以在 shell 循环中使用,如下所示:

\n
for f in *\n    do\n    if [ -h "$f" ]\n        then \n        echo rm -- "$f"\n    fi\ndone\n
Run Code Online (Sandbox Code Playgroud)\n

或者像这样的单行:

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

甚至更紧凑( bash 特定的 \xe2\x80\xa6 尽管据报道也可以在zsh 和 ksh中工作所示:

\n
for f in *; { [ -h "$f" ] && echo rm -- "$f"; }\n
Run Code Online (Sandbox Code Playgroud)\n

注意:

\n

echo是否可以进行空运行...当对输出感到满意时,删除echo以删除链接。

\n