1. Overview

In this short tutorial, we’ll see how to follow symlinks when listing recursively all files in a directory.

To do that, we can use tree, ls, or find. We’ll run those three commands in the same directory so we can compare the output of each.

ls and find are common utilities on Linux and are usually installed by default. However, some distributions don’t install tree by default, but it can be installed through the package manager.

2. Using tree

When using tree, we are presented with a tree-like structure of files and directories.

We only have to add the parameter -l to enable following symlinks because tree always runs recursively:

$ tree -l

Let’s run tree in a folder called example that includes two symlinks — one to a folder and another one to a file:

$ tree -l 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

As we can see, example/sandbox/mytetris is a symlink to another folder, and tree followed it by showing its content. Each symlink is identified with an arrow symbol (->) and its destination.

If there’s a symlink making a loop, tree will print the message “recursive, not followed” and won’t follow it. This behavior is shared – with a similar message – by ls and find.

3. Using ls

We can also use ls to list the content recursively. We just have to include the parameters -R and -L to run it recursively and to follow symlinks, respectively:

$ ls -R -L

Let’s run it with the same folder we used with tree:

$ ls -R -L example
Documents/  sandbox/

contract.pdf  curriculumvitae.pdf  tictactoe_requirements.pdf

mytetris/  tictactoe/

Makefile  tetris.c  tetris.h

requirements.pdf  tictactoe.py

Remember from the previous example that example/sandbox/mytetris and example/Documents/tictactoe_requirements.pdf are symlinks. Notice in this case there is no visual indication of this.

Also, we don’t get the tree-like structure as with tree. We can use more parameters with ls like -l to have more information about the files and folders.

4. Using find

Finally, we have the option to use the find command. We only have to add -L to tell it to follow symlinks, as find will recursively list all files and directories by default:

$ find -L

We’ll use the same example as before but using find. Again, we won’t get any indication that sandbox/mytetris and Documents/tictactoe_requirements.pdf are symlinks:

$ find -L example

5. Conclusion

In this tutorial, we learned how to use the tree, ls, and find commands to follow symlinks.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.