
The tree command is a powerful utility in Linux that displays directory structures in a hierarchical format, making it easy to visualize files and folders within a directory. Unlike the ls command, which lists files in a flat format, tree presents the structure in a tree-like view.
Syntax
tree [OPTIONS] [directory]
- OPTIONS: Various flags that modify the output format.
- directory: The directory path to display. If omitted, the current directory is used.
Installation
The tree command may not be installed by default in some Linux distributions. You can install it using:
Ubuntu/Debian
sudo apt install tree
CentOS/RHEL
sudo yum install tree
Arch Linux
sudo pacman -S tree
Basic Usage and Examples
- Display the Directory Structure
- Show Hidden Files as Well
- Limit Depth to a Specific Level
- Display Only Directories
- Print Full Path of Each File
- Sort Files Alphabetically with Directories First
- Ignore Specific Directories
- Display Tree for a Specific Directory
- Combine Options for Better Output
1. Display the Directory Structure
tree
This command prints the structure of the current directory and its subdirectories.
2. Show Hidden Files as Well
tree -a
By default, hidden files (those starting with .) are not shown. The -a option includes them in the output.
3. Limit Depth to a Specific Level
tree -L 2
This command restricts the output to a maximum depth of 2 levels, making it useful for large directories.
4. Display Only Directories
tree -d
Use this option to list only directories and ignore files.
5. Print Full Path of Each File
tree -f
This command prints the full path of each file and directory instead of just their names.
6. Sort Files Alphabetically with Directories First
tree --dirsfirst
This option arranges directories before files in the output.
7. Ignore Specific Directories
tree -I "node_modules"
This command excludes directories that match the specified pattern. Wildcards can be used (e.g., -I “*.log”).
8. Display Tree for a Specific Directory
tree /home/user
You can specify any directory instead of the current one.
9. Combine Options for Better Output
tree -a -L 2 -d /var/www
This command lists only directories within /var/www, includes hidden ones, and limits the depth to 2 levels.
Conclusion
The tree command is an excellent tool for visualizing directory structures efficiently. It provides various options to filter, format, and customize output to meet specific needs.
Whether you’re managing directories or organizing files, tree simplifies file system navigation in Linux.