In Linux, we use the ls command to display the file listing, i.e., a list of files and directories in a directory. The command is available by default as part of GNU Coreutils.
List Files in Current Directory
When command ‘ls‘ is run without any arguments, it simply shows the file listing of the current directory.
Now, when the ‘ls‘ command is executed, as shown above, it simply lists the immediate contents of the directory and does not deal with the contents of the directories inside the directory, and so on; i.e., the whole file-folder tree structure beneath the directory.
View Whole Directory Structure
To view the whole structure, use the argument
'--recursive' while executing the ls command.
$ ls -R .
With this argument, ls goes down to the very depth of folders until the point where there are no more sub-directories.
However, in some cases, especially when a large number of top-level subdirectories are present in the directory which is being passed as an argument, the output of ‘ls‘ may get ugly, lengthy, and even unnecessarily detailed, due to listing the underlying structure of each and every subdirectory till the very end.
There is no option present in the ‘ls‘ command to deal with this problem, by limiting the depth of file listing.
Install Tree Command in Linux
Hence, to tackle this, we make use of the ‘tree‘ command in Linux. This command is not available by default, and can be installed in Ubuntu and other Debian based distros by running the following:
$ sudo apt install tree [On Debian/Ubuntu & Mint] $ sudo dnf install tree [On RHEL, CentOS & Fedora] $ sudo zypper install tree [On openSUSE] $ sudo pacman -S tree [On Arch Linux]
The ‘tree‘ command shows directory listing in a nicer, more neat format.
You can also pass a directory path as an argument.
$ tree /var/log
As seen in the screenshots above, the command recursively displays the whole file structure without any arguments being passed.
Limit the Depth of Recursive File Listing
To limit the depth of the displayed structure, use the argument ‘-L’.
$ tree -L 3 /home
Now, it has displayed the file listing only 3 levels deep, as opposed to all the way down.
In this article, we have seen how to limit the depth of recursive file display in Linux. Note that apart from the method explained here, using the ‘tree‘ command, other ways are also possible, most popularly, using the find command.
The method using the find command displays the files monotonously without any formatting of the directory structure. If you have any questions or feedback, let us know in the comments below!