
Understanding the Tree Command
1. What is Tree?
Tree is a highly useful command-line tool that visually represents directory structures. It’s particularly valuable when analyzing complex project file structures or during documentation work.
Here’s an example output that helps me understand my project structure and assists with refactoring decisions:
.
├── src/
│ ├── components/
│ │ ├── Header.js
│ │ └── Footer.js
│ └── pages/
│ ├── Home.js
│ └── About.js
└── public/
├── images/
└── styles/
2. Installation Guide
macOS
Install using Homebrew:
brew install tree
Linux (Ubuntu/Debian)
Install using the apt package manager:
sudo apt-get update
sudo apt-get install tree
Linux (CentOS/RHEL)
Install using yum:
sudo yum install tree
Windows
- Download from the official site
- Or install using the Chocolatey package manager:
choco install tree
Verify installation:
tree --version
3. Basic Usage
View Current Directory Structure
tree
View Specific Directory Structure
tree /path/to/directory
Basic Options
-a
: Show hidden files
tree -a
-d
: Show directories only
tree -d
-L n
: Display only n levels deep
tree -L 2
4. Advanced Usage
File Pattern Filtering
Display files matching specific patterns:
tree -P "*.js" # Show only .js files
Exclude specific patterns:
tree -I "node_modules|dist|build" # Exclude node_modules, dist, build directories
Output Formatting
Show file sizes:
tree -sh # Display file sizes in human-readable format
Show file/directory permissions:
tree -p # Display permission information
Show last modification time:
tree -D # Display last modification date
JSON Output
tree -J # Output in JSON format
HTML Output
tree -H "http://localhost" > tree.html # Save as HTML file
5. Practical Examples
Project Documentation
# Add project structure to README.md
tree -L 3 --dirsfirst > project_structure.txt
Large Project Navigation
# Exclude node_modules, show 2 levels deep, directories only
tree -L 2 -d -I "node_modules"
File Size Analysis
# Include file sizes to find large files
tree -sh --du
Git Project Structure Analysis
# Exclude .git and node_modules, show only JavaScript files
tree -I "node_modules|.git" -P "*.js"
6. Common Issues and Solutions
Character Encoding Issues
When special characters or non-ASCII text appears corrupted:
tree --charset unicode
Permission Issues
When encountering “Permission denied” errors:
sudo tree /path/to/directory
Memory Issues
When scanning very large directories:
tree -L 2 # Limit depth to reduce memory usage
Useful Tips
- Setting up aliases
# Add to .bashrc or .zshrc
alias t='tree -L 2' # Show only 2 levels deep
alias td='tree -d' # Show directories only
- Saving Output
tree > structure.txt # Save as text file
tree -H . > structure.html # Save as HTML file
- Using with Pipelines
tree | less # View page by page
tree | grep "\.js$" # Filter JavaScript files only