How to print the directory tree in terminal
What is the command that can be used to draw the directory tree inside the terminal emulator?

3 Answers 3
You can use tree to print the directory tree in terminal. Install tree from terminal,
To see the directory tree, use
Or navigate to a directory and just use
It has some advanced options too. You can see owner’s username , groupname , date of last modification of a file/folder and so on using tree . It supports directory colors of ls so you can see colourized outputs.
Linux ‘tree Command’ Usage Examples for Beginners
The tree is a tiny, cross-platform command-line program used to recursively list or display the content of a directory in a tree-like format. It outputs the directory paths and files in each sub-directory and a summary of a total number of sub-directories and files.
The tree program is available in Unix and Unix-like systems such as Linux, as well as DOS, Windows, and many other operating systems. It features various options for output manipulation, from file options, sorting options, to graphics options, and support for output in XML, JSON and HTML formats.
In this short article, we will show how to use the tree command with examples to recursively list the contents of a directory on a Linux system.
Learn tree Command Usage Examples
The tree command is available on all if not most Linux distributions, however, if you do not have it installed by default, use your default package manager to install it as shown.
Once installed, you can proceed further to learn the tree command usage with examples as shown below.
1. To list directory content in a tree-like format, navigate to the directory you want and run tree command without any options or arguments as follows. Remember to invoke sudo to run the tree in a directory that requires root user access permissions.
It will display the contents of the working directory recursively showing sub-directories and files, and a summary of the total number of sub-directories and files. You can enable the printing of hidden files using the -a flag.

2. To list the directory contents with the full path prefix for each sub-directory and file, use the -f as shown.

3. You can also instruct tree to only print the subdirectories minus the files in them using the -d option. If used together with the -f option, the tree will print the full directory path as shown.

4. You can specify the maximum display depth of the directory tree using the -L option. For example, if you want a depth of 2, run the following command.

Here is another example about setting maximum display depth of the directory tree to 3.

5. To display only those files that match the wild-card pattern, use the -P flag and specify your pattern. In this example, the command will only list files that match cata* , so files such as Catalina.sh, catalina.bat, etc. will be listed.

6. You can also tell the tree to prune empty directories from the output by adding the —prune option, as shown.
7. There are also some useful file options supported by tree such as -p which prints the file type and permissions for each file in a similar way as the ls -l command.

8. Besides, to print the username (or UID if no username is available), of each file, use the -u option, and the -g option prints the group name (or GID if no group name is available). You can combine the -p , -u and -g options to do a long listing similar to ls -l command.

9. You can also print the size of each file in bytes along with the name using the -s option. To print the size of each file but in a more human-readable format, use the -h flag and specify a size letter for kilobytes (K), megabytes (M), gigabytes (G), terabytes (T), etc..

10. To display the date of the last modification time for each sub-directory or file, use the -D options as follows.

11. Another useful option is —du , which reports the size of each sub-directory as the accumulation of sizes of all its files and subdirectories (and their files, and so on).
12. Last but not least, you can send or redirect the tree’s output to filename for later analysis using the -o option.
That’s all with the tree command, run man tree to know more usage and options. If you have any questions or thoughts to share, use the feedback form below to reach us.
Tutorial Feedback.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.
Related Posts






6 thoughts on “Linux ‘tree Command’ Usage Examples for Beginners”
Thanks for the article.
Examples for “tree -f -L X” are mixed. The output of “tree -f -L 3” is the one of “tree -f -L 2“.
Aaron, the tree command will not run on Centos 7, can you confirm what distro/version of Linux you’re using?
All good now after rerunning the ‘ yum install tree ‘ command.
Ok, it’s good that you discovered how to get it working on CentOS. Thanks for the feedback.
Bash: использование команды tree для отображения структуры папок

Цель этого руководства — понять данные JSON и понять, как анализировать данные JSON в C ++. Мы обсудим данные JSON, объект, массив, синтаксис JSON, а затем рассмотрим несколько рабочих примеров, чтобы понять механизм анализа данных JSON в C ++.
Команда «tree» — это очень широко используемая команда Bash в Linux. Он используется для отображения содержимого любого желаемого каталога вашей компьютерной системы в виде древовидной структуры. Используя эту древовидную структуру, вы можете легко узнать пути к своим файлам и каталогам, проверить их права доступа и просмотреть скрытые файлы и каталоги. Поэтому сегодня мы поговорим об использовании команды Bash «tree» в Linux Mint 20, поделившись с вами некоторыми примерами.
Команда Bash Tree в Linux Mint 20
Чтобы использовать команду Bash «tree» в Linux Mint 20, вам сначала необходимо установить ее, выполнив эту команду:

Было бы неплохо, если бы вы могли обновить свою систему перед запуском этой команды. После успешной установки команды tree в вашей системе Linux Mint 20 вы получите следующие сообщения на своем терминале:

Теперь, чтобы проверить, действительно ли команда Bash «tree» находится в вашей системе Linux Mint 20 или нет, вы можете проверить ее версию, выполнив команду, указанную ниже:

Версия команды Bash «tree», которую нам удалось установить только что, выделена на следующем изображении:

После этого вы можете проверить синтаксис и все доступные параметры для этой команды, чтобы вы могли использовать ее эффективно. Вы можете найти эту информацию, выполнив команду, указанную ниже:

Выполнение этой команды отобразит всю необходимую информацию о команде Bash «tree», включая ее синтаксис, которая вам понадобится для работы с этой командой без каких-либо затруднений. Вы можете потратить некоторое время на это, чтобы хорошо изучить все доступные варианты.

После выполнения этих шагов мы хотели бы поделиться с вами некоторыми из наиболее полезных примеров использования команды Bash «tree» в Linux Mint 20.
Пример №1: Отображение содержимого каталога в древовидной структуре
Древовидные структуры обычно легче визуализировать и интерпретировать по сравнению с обычным текстовым представлением. Следовательно, если у вас есть каталог, содержащий множество разных файлов и подкаталогов, вам следует предпочесть просматривать его содержимое в древовидной структуре. Это легко сделать, выполнив команду tree, как показано ниже:

Древовидная структура нашего текущего рабочего каталога показана на следующем изображении. Здесь следует отметить, что простая команда «tree» не отображает скрытые файлы и каталоги. Вот почему количество файлов и каталогов, отображаемых в выводе этой команды, очень мало.

Пример № 2: Отображение скрытых файлов и каталогов с помощью древовидной команды
В отличие от простого «дерева», вы также можете просмотреть скрытые файлы и каталоги. Вы можете сделать это просто, запустив команду «tree» с флагом «-a», как показано ниже:

Вы можете сравнить вывод этой команды с выводом, показанным в примере № 1, и вы сможете понять, что количество файлов и каталогов намного больше, чем показано выше. Это потому, что на этот раз команда «tree» также показала скрытые файлы и каталоги.

Пример № 3: Отображение файлов и каталогов вместе с их полными путями
Вместо того, чтобы отображать только имена файлов и каталогов, вы также можете узнать их точные пути. Вы можете сделать это, просто объединив команду «tree» с флагом «-f» следующим образом:

Пути ко всем файлам и каталогам в нашем текущем рабочем каталоге показаны ниже в виде древовидной структуры. Если бы вы выполняли команду «tree» в каталоге, отличном от «Home», тогда концепция путей была бы более ясной. Однако в нашем случае, поскольку мы выполнили команду «tree», находясь в «домашнем» каталоге, именно поэтому вы можете видеть только «./» вместо пути к файлу или каталогу, поскольку он представляет «домашний» каталог.

Пример №4: Распечатать дерево каталогов в XML-представлении
XML или Extensible Markup Language имеет особый синтаксис, в котором он представляет наши файлы и каталоги. Следовательно, если вы хотите распечатать свое дерево каталогов в XML-представлении, вы можете сделать это, объединив флаг «-X» с командой «tree» следующим образом:

XML-представление нашего дерева каталогов показано на изображении ниже:

Пример № 5: Отображение файлов и каталогов вместе с их разрешениями на доступ
Разрешения для файлов и каталогов считаются очень важными, особенно если мы хотим иметь дело с политиками управления доступом в операционной системе. Если вы хотите, чтобы права доступа к файлам и каталогам отображались в дереве каталогов, вам нужно будет выполнить команду «tree» с флагом «-p».

Разрешения на «чтение», «запись» и «выполнение» показаны перед каждым именем файла и каталога в нашей структуре каталогов, как показано на следующем изображении. Кроме того, права доступа к каталогу также включают флаг «d», который указывает, что следующее имя относится к каталогу, а не к файлу.

Заключение
В сегодняшней статье мы рассказали вам о методе установки команды Bash «tree» в вашей системе Linux Mint 20. Мы продемонстрировали метод проверки его установки, а также доступ к страницам справки. Затем мы поделились с вами пятью наиболее важными сценариями, в которых команда «tree» может использоваться очень эффективно. Помимо этих пяти сценариев, существует множество других вариантов использования команды Bash «tree». Вкратце, эта команда Bash считается чрезвычайно полезной при работе с операционными системами на базе Linux.
How To View Directory Tree Structure In Linux
Today, we are going to learn how to view directory structure using Tree command. As the name says, the tree command will display the contents of a directory in a tree-like format in Linux and Unix-like operating systems.
You might wonder why would someone use this command while we already have ls command to list the contents of a directory.
Unlike ls command, Tree command is a recursive directory listing program that produces a depth indented listing of files. It is quite useful to find the directories that contains lot of sub-directories in Unix-like systems.
Install tree in Linux
Tree command is available in the default repositories of most Linux distributions. So, it can be installed from the distribution’s default package manager as shown below.
On Arch Linux and its derivatives:
On RHEL, CentOS, Fedora:
On Debian, Linux Mint, Pop OS and Ubuntu:
We have installed tree utility. Now, let us see some practical examples.
View Directory Tree Structure In Linux
If you run the tree command without any arguments, the tree command will display all contents of the current working directory in a tree-like format.
Sample output:

Tree command output
Upon completion of listing all files/directories found, tree returns the total number of files and/or directories listed. As you see in the above output, the current directory contains 3321 sub-directories, and 40023 files.
To list the files of the specific directory in a tree-like format, say for example /etc , run:
Sample output:

View directory tree structure
By default, Tree will not list the hidden files. If you want to list the hidden files, use -a parameter like below.
Sample output:

List the hidden files using tree command
Now, check the above output. The total of number of directories and files are higher than the previous output. It is because, this time the tree command lists all directories and files including hidden files.
To view the directory structure in a colored format, use -C parameter.
Sample output:

View directory structure in color
Did you notice that the tree command lists the directories and files in different colors? Yes! This is will useful to easily distinguish the directories and files.
As you may have noticed, all of the above commands lists the sub-directories and files. You can also list only the directories using -d parameter like below.
Sample output:

List only directory structure and exclude sub-directories
You can also display the directory listing line by line using the following command:
Press ENTER to navigate through the output.
By default, Tree command will list all sub-directories and the files inside the main directory. To limit the depth or of level of recursion, use -L parameter like below.
Here, L indicates the maximum display depth of the directory tree.
For more details, refer the man pages.
Conclusion
As you can see in this guide, tree command will give you a nice graphical tree view of the directory structure. You can use this command when you want to view the contents of directories that have tons of other files/folders nested inside their folders.
Senthilkumar Palani (aka SK) is the Founder and Editor in chief of OSTechNix. He is a Linux/Unix enthusiast and FOSS supporter. He lives in Tamilnadu, India.