When navigating a Linux file system using the command line, the standard ls command is excellent for viewing the immediate contents of a single directory. However, if you need to understand the complex hierarchy of a massive project folder—such as a website’s source code containing dozens of nested subdirectories for CSS, JavaScript, and image assets—running ls repeatedly while constantly changing directories (cd) is incredibly tedious. The Linux tree command solves this by visually mapping out the entire directory structure in a clear, indented, tree-like format directly in your terminal.
Installing the tree Command
Unlike ls or cd, the tree command is not always installed by default on every Linux distribution (especially minimal server installs like Ubuntu Server or Debian). If you type tree and receive a “command not found” error, you must install it via your package manager.
- On Ubuntu/Debian:
sudo apt update && sudo apt install tree - On RHEL/CentOS/Fedora:
sudo dnf install tree
Basic Usage and Understanding the Output
To use the command, simply navigate to the directory you want to inspect (or provide the path as an argument) and run it.
tree /var/www/html/
The terminal will output a visual diagram using ASCII characters to draw lines connecting parent folders to their child folders and files. At the very bottom of the output, tree provides a highly useful summary report, such as: 14 directories, 52 files. This allows you to instantly gauge the complexity and size of a project.
Controlling the Depth of the Tree
If you run tree on the root directory (/), it will attempt to map every single file on your entire hard drive, resulting in millions of lines of output that will freeze your terminal. To prevent this, you should restrict how deep the command is allowed to search using the -L (Level) flag.
tree -L 2 /etc/
This command tells tree to map the /etc/ directory, but only go down a maximum of 2 levels deep. It will show the immediate subdirectories and the files inside them, but it will not drill down into any further nested folders, keeping the output concise and readable.
Filtering the Output
The tree command offers several powerful flags to filter exactly what is displayed on the screen, which is invaluable when searching for specific assets.
- Show only directories: If you don’t care about the individual files and only want to see the folder structure, use the
-dflag.tree -d /home/user/Projects/ - Show hidden files: Like the
lscommand,treeignores hidden files and folders (those starting with a dot, like.gitor.env) by default. To force it to display everything, use the-a(all) flag.tree -a /var/www/ - Filter by file pattern: If you only want to see where the Python scripts are located within a massive project, you can use the
-P(Pattern) flag followed by a wildcard.tree -P "*.py" /home/user/scripts/