Linux tree Command: Display a Directory Tree

`tree` is a command that displays the hierarchical structure of directories and files in an indented tree format. It is useful for browsing the entire current directory or limiting the output depth and selecting specific files to check the project structure.

This explains frequently used methods, from basic installation to showing hidden files, exclusion patterns, checking file size and permissions, and saving text or JSON. The examples are based on the `tree` for Unix/Linux.

What is the tree command?

`tree` recursively explores the specified directory and prints the relationship between files and subdirectories indented according to depth. If no directory is specified, it targets the current directory `.`.

tree

For example, you can see the following structure at a glance.

.
├── README.md
├── config
│   └── app.conf
├── public
│   └── index.html
└── src
    ├── main.py
    └── utils.py

3 directories, 5 files

While `ls` also shows a list of files, it is basically suitable for checking items in a single directory. `tree` is more convenient for visually understanding multiple levels of inclusion.

Installing tree

`tree` is not a shell built-in command and may not be installed by default depending on the distribution. First, check whether it is installed with the following command.

tree --version

Debian and Ubuntu

sudo apt update
sudo apt install tree

Rocky Linux, AlmaLinux, RHEL, and Fedora

sudo dnf install tree

On older distributions that use yum instead of dnf, you can use sudo yum install tree. The package must be available in an enabled repository to be installed.

Arch Linux

sudo pacman -S tree

Basic Syntax and Usage

tree [options] [directory...]

To print the current directory, run it without any arguments, and to check a different location, specify the path. You can also specify multiple directories at once.

tree
tree /etc/nginx
tree ~/projects/app
tree src tests

Paths with spaces should be enclosed in quotes so that they are passed as a single argument.

tree "Project Files"

By default, the output ends with the count of directories and files explored. If you don't need this summary, use --noreport.

tree --noreport

Specify the target directory and output depth

View a specific directory structure

You can specify the directory to check as an argument without changing the current location.

tree /var/www
tree ./src

Specifying the path separates the command execution location and the output target, making it easier to understand the intention even in automation.

Limit the maximum depth with -L

For large projects or system directories, outputting everything can result in an excessively long output. Specify the maximum depth to display after -L.

tree -L 1
tree -L 2 /var/www
tree -L 3 ~/projects/app

tree -L 2 displays only up to two levels from the starting point. When sharing directory structures, it's better to limit the depth first so that only the necessary range is visible.

Display only hidden files and directories

Include hidden files with -a

By default, hidden files and directories whose names start with a dot are not included in the output. Using -a will also display items like .env and .gitignore.

tree -a
tree -a -L 2

When sharing configuration file names or directory structures externally, make sure no sensitive information is exposed. -a outputs the names, not the contents, but the names themselves can be sensitive.

Display only directories with -d

To check only the folder structure excluding files, use -d.

tree -d
tree -d -L 3 /var/www

It is useful when quickly explaining the module composition of a project or the layout of backup directories.

Include or exclude by file name

It is safe to enclose the patterns of -P and -I in single quotes so that the shell does not expand them first. Multiple patterns can be separated by the vertical bar |.

Display only files matching with -P

-P selects only files that match the wildcard pattern.

tree -P '*.py'
tree -P '*.jpg|*.png|*.webp'

To remove even directories that appear empty after filtering, use --prune together.

tree -P '*.py' --prune

To include hidden files in pattern checking, you additionally need -a.

Excluding unnecessary items with -I

-I excludes files and directories that match the pattern from the output. Hiding dependency, build results, and cache directories makes the project structure much simpler.

tree -I 'node_modules|.git|dist|__pycache__'
tree -L 3 -I '*.log|tmp|cache'

-I excludes files only from display, without deleting them.

Using Git ignore rules with --gitignore

In supported versions, --gitignore allows you to use the rules from .gitignore and Git exclude files in the filter.

tree --gitignore
tree -a --gitignore -L 3

Check if your installed version supports this option with tree --help. Even when using --gitignore, you should review the output manually before sharing the repository structure externally.

Display size, permissions, and modification time

Viewing File Size and Cumulative Directory Size

-s shows the size in bytes, and if you use -h together, it displays the size in a human-readable format.

tree -s
tree -h

--du calculates the cumulative size of files and subdirectories contained in each directory. If you want a human-readable format, use -h together.

tree --du -h -L 2

--du reads the entire tree, calculates the size, and then outputs it, so it may take a long time and use a lot of memory for large directories.

Viewing Permissions, Owner, and Time

-p shows permissions, -u shows the owner, and -g shows the group. Adding -D lets you also see the last modification time.

tree -p
tree -pug
tree -pugD -L 2

When investigating permission issues, you can see both the structure and metadata, but if there are very long usernames and paths, the output width may become wide.

Changing Sort Order and Path Display

Display and sort directories first

--dirsfirst places directories before files. -t sorts by modification time, --sort=size sorts by size, and -r reverses the result order.

tree --dirsfirst
tree -t
tree --sort=size -r

To use the order stored in the file system as-is and reduce sorting cost, you can use -U. In this case, --dirsfirst is disabled.

Create full paths and concise lists

-f displays the full path prefix before each item. -i removes the branch-shaped indentation lines.

tree -f
tree -fi --noreport

If you need a simple path list for reading in other commands, the combination -fi --noreport is convenient. However, if file names contain special characters like newlines, simple text parsing may not be safe.

Save results to a file and structured format

Save as a text file

-o sends the output results to the specified file.

tree -L 3 -o directory-structure.txt
tree -a -I '.git|node_modules' --noreport -o project-tree.txt

You can also use shell redirection. You can turn off colors with -n to prevent color control characters from mixing into the file.

tree -n -L 3 > directory-structure.txt

Outputting in JSON and XML

-J outputs in JSON, and -X outputs in XML format. It can be used when analyzing or transforming the structure in subsequent programs.

tree -J -L 3 > directory-structure.json
tree -X -L 3 > directory-structure.xml

The structured output format and provided fields may vary depending on the installed tree version, so check the actual output first when creating a consumer program.

Handling symbolic links and filesystem boundaries

Deciding whether to follow symbolic links

By default, symbolic links display the link name and target path, but they do not enter the directories they point to. Using -l follows symbolic links pointing to directories.

tree -l -L 3

Following links can explore more paths than expected, so it is safer to use a depth limit together. The tool avoids detected recursive links, but you need to check the output range and processing time yourself.

Stay on the current filesystem with -x

-x prevents moving into a different file system from the starting directory. It is useful for limiting the exploration range on servers with many mount points.

tree -x -L 3 /

Even when targeting the root directory, paths without permission cannot be read, and printing the structure of the entire system can produce very large results.

Frequently used tree command combinations

Command Purpose
tree Displays the files and subdirectories of the current directory as a tree.
tree -L 2 Displays only up to two levels from the current location.
tree -a Includes hidden files and hidden directories as well.
tree -d Displays directories only, excluding files.
tree -I 'node_modules|.git' Excludes files and directories that match the specified pattern.
tree -P '*.py' --prune Displays centered around branches containing Python files.
tree -h --du -L 2 Displays the cumulative size of directories up to two levels in a readable format.
tree -pugD Displays permissions, user, group, and modification time together.
tree -fi --noreport Generates a full path list without branch lines and summary.
tree -J -L 3 Outputs the structure up to three levels as JSON.

Summary of major options

Option Description
-a Includes hidden files and directories starting with a dot.
-d Displays directories only.
-L number Limits the maximum directory depth to display.
-P pattern Selects files that match the wildcard pattern.
-I pattern Excludes files and directories that match the wildcard pattern.
--prune Removes empty directories from the output after applying filters.
--gitignore Uses Git-excluded file rules for filtering.
-f Displays the full path prefix before each file name.
-h Shows file sizes in human-readable units.
--du Calculates cumulative sizes by directory.
-p Displays file types and permissions.
-D Shows the last modification time.
--dirsfirst Sorts directories before files.
-J Outputs in JSON format.
-X Output in XML format.
-o FILE Save the output to the specified file.
-l Follow symbolic links that point to directories.
-x Search only within the same filesystem as the starting location.
--noreport Omit the summary of the number of files and directories at the end.

Points to be careful when using in large directories

Limit depth and filters first

If you search the root directory, the entire user home, or large dependency directories without restrictions, the output and processing time will increase significantly. First, limit the depth with -L and exclude unnecessary branches with -I or --gitignore.

Understand the cost of --du and --prune

--du and --prune may need to collect the entire tree in memory before producing results. In very large directories, the output may be delayed and memory usage may increase.

Checking for permission errors and sensitive names

Directories that the current user does not have read or navigate permissions for will not be fully displayed. Simply running as an administrator to see the entire structure may unnecessarily expand access, so first check the required paths and permissions.

Before attaching output files to documents or issues, review to ensure user names, internal server paths, secret file names, and project codenames are not included.

FAQ

tree: command not found - why does this error occur?

This occurs because tree is not installed or the executable path is not in PATH. Install the tree package using your distribution's package manager and check with tree --version.

How can I view subdirectories up to only two levels?

Use tree -L 2. To check a different path, specify the directory at the end like tree -L 2 /path/to/check.

Can I exclude the node_modules and.git directories at once?

Use tree -I 'node_modules|.git'. Wrapping the pattern in single quotes prevents the shell from interpreting the vertical bar or wildcards first.

How can I format the tree output nicely for a README?

Limit depth and exclusions like tree -L 3 -I '.git|node_modules|dist' --noreport. After ensuring that the output does not contain internal paths or sensitive file names, you can place it in a code block to preserve the structure.

Related articles and official documentation

More in This Category
Linux Tutorial / Find Files and Commands with find, locate, which, and whereis

Linux Tutorial / Find Files and Commands with find, locate, which, and whereis

Compare find and locate for file searches, then use which, whereis, and Bash type to distinguish executable paths from shell command resolution.

Linux less Command: Browse and Search Long Text Files

Linux less Command: Browse and Search Long Text Files

Learn how to browse long files with Linux less, move forward and backward, search text, follow growing logs, preserve colors, and exit the pager.

Linux Tutorial / Linux Terminal and Shell Basics: Command Syntax and Finding Help

Linux Tutorial / Linux Terminal and Shell Basics: Command Syntax and Finding Help

Learn the difference between a terminal and a shell, read command syntax and output, and use Bash help tools through a short hands-on exercise.

Linux tr Command: Translate and Delete Characters

Linux tr Command: Translate and Delete Characters

Learn how to translate and Delete Characters with the Linux tr command, including practical examples, key options, and important precautions.

Linux machine-id: How to Check and Reset It for Cloned Systems

Linux machine-id: How to Check and Reset It for Cloned Systems

Learn what the Linux machine-id identifies, how to check it, and how to prepare cloned system images for unique IDs. Understand the difference between an empty file and first-boot initialization.

Best Linux Distributions for Web Servers: Ubuntu, Debian, or Rocky Linux?

Best Linux Distributions for Web Servers: Ubuntu, Debian, or Rocky Linux?

Compare Ubuntu Server, Debian, and Rocky Linux for web hosting based on support lifecycle, package freshness, documentation, operational stability, and application requirements.

Linux sort Command: Sort Text Lines

Linux sort Command: Sort Text Lines

Learn how to sort text lines with the Linux sort command, including practical examples, key options, and important precautions.

Linux id Command: Show User and Group IDs

Linux id Command: Show User and Group IDs

Learn how to show User and Group IDs with the Linux id command, including practical examples, key options, and important precautions.

Linux fsck Command: Check and Repair Filesystems

Linux fsck Command: Check and Repair Filesystems

Learn how to check and Repair Filesystems with the Linux fsck command, including practical examples, key options, and important precautions.

Linux top Command: Monitor Processes in Real Time

Linux top Command: Monitor Processes in Real Time

Learn how to monitor Processes in Real Time with the Linux top command, including practical examples, key options, and important precautions.