Lesson 16: tree Command
In this lesson, you'll learn how to use the tree command to recursively list and display the contents of a directory in a tree-like format in Linux.
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 the 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.
Let's now use the tree command with examples to recursively list the contents of a directory on a Linux system.
Install tree on Linux
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.
# yum install tree #RHEL/CentOS 7
# dnf install tree #Fedora 22+ and RHEL/CentOS 8
$ sudo apt install tree #Ubuntu/Debian
# sudo zypper in tree #openSUSE
Once installed, you can proceed further to learn the tree command usage with examples as shown below.
tree Command Syntax
tree [OPTIONS] [DIRECTORY]
tree Command Options
| Option | Description |
|---|---|
-a |
Print all files including hidden files |
-d |
List directories only |
-f |
Print the full path prefix for each file |
-L N |
Set the maximum display depth to N levels |
-P pattern |
List only files that match the wildcard pattern |
--prune |
Prune empty directories from the output |
-p |
Print file type and permissions for each file |
-u |
Print the username or UID of each file |
-g |
Print the group name or GID of each file |
-s |
Print the size of each file in bytes |
-h |
Print file sizes in human-readable format |
-D |
Print the date of the last modification time |
--du |
Report the size of each directory as the accumulation of all its files |
-o filename |
Send output to a file |
1. List Directory Content in Tree Format
To list directory content in a tree-like format, navigate to the directory you want and run the tree command without any options or arguments as follows.
Remember to invoke sudo to run tree in a directory that requires root user access permissions.
# tree
Or:
$ sudo tree
.
βββ Desktop
βββ Documents
β βββ report.pdf
β βββ resume.docx
βββ Downloads
β βββ archive.zip
βββ notes.txt
3 directories, 4 files
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.
$ sudo tree -a
.
βββ .bash_logout
βββ .bashrc
βββ .profile
βββ Desktop
βββ Documents
β βββ report.pdf
β βββ resume.docx
βββ notes.txt
3 directories, 6 files