Contents

递归列出目录中的所有文件,包括链接

1. 概述

在这个简短的教程中,我们将了解在递归列出目录中的所有文件时如何遵循符号链接 。 为此,*我们可以使用tree ls find *。**我们将在同一目录中运行这三个命令,以便比较每个命令的输出。

lsfind是 Linux 上的常用实用程序,通常默认安装。但是,有些发行版默认不安装tree,但可以通过包管理器 安装。

2. 使用tree

使用tree 时,我们会看到文件和目录的树状结构。

我们只需要添加参数-l来启用以下符号链接,因为tree*总是递归运行*:

$ tree -l

让我们在一个名为example的文件夹中运行tree,该文件夹包含两个符号链接——一个指向文件夹,另一个指向文件:

$ tree -l example
example
├── Documents
│   ├── contract.pdf
│   ├── curriculumvitae.pdf
│   └── tictactoe_requirements.pdf -> ../sandbox/tictactoe/requirements.pdf
└── sandbox
    ├── mytetris -> ../../mytetris
    │   ├── Makefile
    │   ├── tetris.c
    │   └── tetris.h
    └── tictactoe
        ├── requirements.pdf
        └── tictactoe.py
4 directories, 8 files

正如我们所见,example/sandbox/mytetris是指向另一个文件夹的符号链接,tree紧随其后显示其内容。每个符号链接都用箭头符号 ( -> ) 及其目的地标识。

如果有一个符号链接形成一个循环,tree将打印消息“ recursive, not followed ”并且不会跟随它。此行为由lsfind共享(带有类似的消息)。

3. 使用ls

**我们还可以使用ls递归地列出内容。*我们只需要分别包含参数-R-L*以递归运行它并遵循符号链接:

$ ls -R -L

让我们使用与tree相同的文件夹运行它:

$ ls -R -L example
example:
Documents/  sandbox/
example/Documents:
contract.pdf  curriculumvitae.pdf  tictactoe_requirements.pdf
example/sandbox:
mytetris/  tictactoe/
example/sandbox/mytetris:
Makefile  tetris.c  tetris.h
example/sandbox/tictactoe:
requirements.pdf  tictactoe.py

请记住前面的示例,example/sandbox/mytetrisexample/Documents/tictactoe_requirements.pdf是符号链接。请注意,在这种情况下,没有视觉指示。

此外,我们没有像 tree 那样得到树状结构。我们可以在ls中使用更多参数,例如*-l*以获得有关文件和文件夹的更多信息。

4. 使用find

最后,我们可以选择使用find命令。我们只需要添加-L来告诉它遵循符号链接,因为默认情况下find*将递归列出所有文件和目录:*

$ find -L

我们将使用与之前相同的示例,但使用find。同样,我们不会得到任何表明sandbox/mytetrisDocuments/tictactoe_requirements.pdf是符号链接的迹象:

$ find -L example
example
example/sandbox
example/sandbox/mytetris
example/sandbox/mytetris/Makefile
example/sandbox/mytetris/tetris.c
example/sandbox/mytetris/tetris.h
example/sandbox/tictactoe
example/sandbox/tictactoe/requirements.pdf
example/sandbox/tictactoe/tictactoe.py
example/Documents
example/Documents/contract.pdf
example/Documents/curriculumvitae.pdf
example/Documents/tictactoe_requirements.pdf