In Linux, everything is a file even the “directories” are considered as the “directory files”. A single directory may contain some files and sub-directories. Applying any operation to files and subdirectories of a directory is known as a recursive operation.
This guide enlists all possible ways to list only directories recursively in Linux with the following guideline:
Method 1: Using the “ls” Command to List Directories Recursively
The “ls(list)” is the most frequently used command that lists all files, directories, and subdirectories located in the current directory. In this method, it is used with the combination of its “-l(list in table format)” and “-R(recursively)” flags to list directories along its content:
$ ls -lR
The above command is first listed the available directories and then displayed their content (files and subdirectories).
Method 2: Using the “du” Command to List Directories Recursively
The main objective of the “du(disk usage)” pre-installedcommand is to check the file space usage quickly. It generally checks how much space is occupied by files and directories.
The “du” command with the “-a(all)” flag is used with the path of the directory to list down the only directories recursively, as shown below:
$ du –a
The output shows all the available files and subdirectories of “Sample” directory with its parent directory and size.
Method 3: Using the “find” Command to List Directories Recursively
The “find” command searches the files and directories in the Linux system based on the specified conditions or arguments.
The “find” command lists down the directories recursively by simply running it on the terminal(Ctrl+ALT+T):
$ find /home/itslinuxfoss/test
The output displays all the files and subdirectories of the “test” directory along thor absolute path.
Method 4: Using the “tree” Command to List Directories Recursively
The “tree” command refers to the recursive directory that shows the files in the hierarchical(parent-child) format.
Installing tree Command on LInux:
$ sudo yum install tree # For RHEL/CentOS/Fedora $ sudo apt install tree #For Ubuntu/Debian-based
When installed, use it without any flag or argument just to list down the specific directory recursively. Here, it is used to view the data of the “Music” directory for practical implementation:
$ tree /home/itslinuxfoss/Music
The above command has executed successfully and shows the hierarchy of the “Music” directory as it contains “4 directories and 5 files”.
To list only directories recursively in Linux, use the “ls(list)”, “du(disk usage)”, “find”, and “tree” commands. The “ls” list the directories (recursively) in the sequence format, while the “find”, tree”, and “du” command shows the content of the directory in hierarchal (parent-child relationship) format.
This guide has provided all the possible aspects to list only directories recursively.