The Linux Tree Command: A Comprehensive Guide

The tree command is a powerful recursive directory listing utility for Linux and Unix-like operating systems that displays the contents of directories in a hierarchical, tree-like format. Unlike basic commands like ls, tree provides an intuitive visual representation of the entire directory structure, making it invaluable for understanding complex file hierarchies, documenting project structures, and quickly navigating through nested directories.

Originally developed for Unix systems, tree has become a cross-platform tool available on Linux, macOS, Windows, and other operating systems. It offers extensive customization options ranging from filtering and sorting to multiple output formats including HTML, XML, and JSON.

Installation

The tree command is not installed by default on most Linux distributions, but it’s readily available in official repositories.

Red Hat/CentOS/Fedora

For RHEL/CentOS 7:

sudo yum install tree

For RHEL/CentOS 8+, Fedora, Rocky Linux, and Alma Linux:

sudo dnf install tree

Debian/Ubuntu/Mint

sudo apt install tree

Or using apt-get:

sudo apt-get install tree

Arch Linux

sudo pacman -Syu tree

openSUSE/SUSE

sudo zypper in tree

Alpine Linux

apk add tree

macOS

Using Homebrew:

brew install tree

Basic Usage

Simple Invocation

The most basic usage requires no options:

tree

This displays the complete hierarchical structure of the current working directory, showing all subdirectories and files in a tree-like format with a summary of total directories and files at the end.

Example Output

.
├── config.dat
├── data
│   ├── data1.bin
│   ├── data2.sql
│   └── data3.inf
├── images
│   ├── background.jpg
│   ├── icon.gif
│   └── logo.jpg
├── program.exe
└── readme.txt

2 directories, 9 files

Specifying a Directory

To display the tree structure of a specific directory:

tree /path/to/directory

Multiple directories can be specified, and tree will list each in turn.

Essential Options

Display Hidden Files (-a)

By default, tree doesn’t display hidden files (those beginning with a dot). The -a option includes all files:

tree -a

Note that tree never prints the filesystem constructs . (current directory) and .. (parent directory).

Directories Only (-d)

To display only directories without files:

tree -d

This is particularly useful for understanding the overall structure of large projects without file clutter.

Full Path Prefix (-f)

Print the full path prefix for each file:

tree -f

Example output:

.
├── ./backups
│   ├── ./backups/apache.log
│   ├── ./backups/bck.log
│   └── ./backups/sys.log
└── ./ipsum.txt

Limiting Display Depth (-L)

Control how deep into the directory tree the command descends using the -L option:

tree -L 2

This limits the output to two levels of directories. This is extremely useful for large directory structures where you only want an overview.

ASCII Line Graphics (-A)

Use ASCII characters for the tree structure instead of the default Unicode box-drawing characters:

tree -A

This option is useful for compatibility with systems that don’t support Unicode properly.

File Information Options

File Permissions (-p)

Display file type and permissions (similar to ls -l):

tree -p

Example output:

.
├── [drwxrwxr-x]  backups
│   ├── [-rw-rw-r--]  apache.log
│   └── [-rw-rw-r--]  sys.log
└── [-rw-rw-r--]  newFile.txt

File Size (-s and -h)

Print the size of each file in bytes:

tree -s

For human-readable sizes with unit suffixes (K, M, G, T, P, E):

tree -h

You can combine these for detailed file information:

tree -psh

User and Group Information (-u and -g)

Display the username (or UID if unavailable):

tree -u

Display the group name (or GID if unavailable):

tree -g

Combine all file information options for a detailed listing:

tree -pugh

Last Modification Date (-D)

Display the date of last modification:

tree -D

For custom date formatting, use --timefmt:

tree -D --timefmt "%Y-%m-%d %H:%M"

This uses strftime(3) syntax for the format string.

Filtering and Pattern Matching

Include Pattern (-P)

Display only files matching a wildcard pattern:

tree -P "*.txt"

To include hidden files in pattern matching, combine with -a:

tree -a -P "*.log"

Exclude Pattern (-I)

Omit files matching a pattern:

tree -I "*.tmp"

You can exclude multiple patterns:

tree -I "node_modules|*.log|.git"

This is particularly useful for excluding common directories like node_modules, .git, or build artifacts.

Prune Empty Directories (–prune)

Remove empty directories from the output:

tree --prune

File Limit (–filelimit)

Don’t descend directories that contain more than a specified number of entries:

tree --filelimit 100

This prevents tree from getting overwhelmed by directories with thousands of files.

Sorting Options

Sort by Modification Time (-t)

Sort files by last modification time instead of alphabetically (most recent first):

tree -t

Reverse Sort (-r)

Reverse the sort order:

tree -r

Directories First (–dirsfirst)

List directories before files at each level:

tree --dirsfirst

Output Control

No Report (–noreport)

Omit the file and directory count at the end of the tree listing:

tree --noreport

Color Output (-C)

Turn on color output (uses LS_COLORS environment variable):

tree -C

Color is automatically enabled if output is to a terminal and the LS_COLORS variable is set.

Turn Off Colors (-n)

Explicitly disable color output:

tree -n

No Indentation (-i)

Don’t print indentation lines:

tree -i

This is useful when combined with the -f option for producing simple file lists with full paths.

File Type Indicators (-F)

Append indicators to filenames:

  • / for directories
  • = for socket files
  • * for executable files
  • | for FIFO pipes
tree -F

Advanced Features

By default, tree shows the path that symbolic links point to in the format: link -> target

To follow symbolic links to directories as if they were directories:

tree -l

Tree detects and avoids recursive symbolic links.

Stay on Current Filesystem (-x)

Prevent tree from crossing filesystem boundaries (similar to find -xdev):

tree -x

Device Numbers (–device)

Display the device number associated with each file:

tree --device

Inode Numbers (–inodes)

Display inode numbers:

tree --inodes

Disk Usage (–du)

Display the size of each directory as the accumulation of sizes of all its files and subdirectories:

tree --du -h

Combine with -h for human-readable sizes.

Output Formats

XML Output (-X)

Generate XML-formatted output:

tree -X > directory_structure.xml

Example XML output:

<?xml version="1.0" encoding="UTF-8"?>
<tree>
  <directory name=".">
    <file name="config.dat" size="1024"></file>
    <directory name="data">
      <file name="data1.bin" size="2048"></file>
    </directory>
  </directory>
</tree>

JSON Output (-J)

Generate JSON-formatted output:

tree -J > directory_structure.json

Example JSON output:

[
  {
    "type": "directory",
    "name": ".",
    "contents": [
      {
        "type": "file",
        "name": "config.dat"
      },
      {
        "type": "directory",
        "name": "data",
        "contents": [
          {
            "type": "file",
            "name": "data1.bin"
          }
        ]
      }
    ]
  }
]

HTML Output (-H)

Generate HTML output with hyperlinks:

tree -H 'http://example.com' -o output.html

The base HREF specifies the base location for links. For example, if the local directory is /local/ftp/pub but should be referenced as ftp://hostname.domain.com/pub, use:

tree -H 'ftp://hostname.domain.com/pub' /local/ftp/pub

Additional HTML options:

  • -T: Set the title and H1 header
  • --nolinks: Turn off hyperlinks
  • -C: Force color output via CSS stylesheet

Example with full options:

tree -H './' -T "Project Structure" -C --nolinks -o structure.html

Output Redirection

Save to File (-o)

Write output to a specified file:

tree -o directory_structure.txt

Or use standard shell redirection:

tree > directory_structure.txt

For JSON documentation:

tree -J -o structure.json

Practical Examples

Document a Project Structure

tree -L 3 --dirsfirst -I "node_modules|.git|build" > PROJECT_STRUCTURE.md

This creates a three-level deep structure, lists directories first, and excludes common development directories.

Find All Configuration Files

tree -P "*.conf|*.config|*.cfg" --prune

This shows only configuration files and prunes empty directories.

Show Only Python Files with Details

tree -phD -P "*.py"

This displays Python files with permissions, human-readable sizes, and modification dates.

Generate Documentation Website

tree -H './' -T "API Documentation" -L 2 -C -o api-structure.html

This creates an HTML page with colored output showing two levels of the directory structure.

Quick Size Analysis

tree --du -h -d -L 2

This shows directory sizes in human-readable format for the first two levels, directories only.

Export Directory Structure as JSON

tree -J -o project-structure.json

This is useful for programmatic processing of directory structures or integration with other tools.

Audit Log Files with Timestamps

tree -D --timefmt "%Y-%m-%d %H:%M:%S" -P "*.log" /var/log

This lists all log files with detailed timestamps.

Compare Directory Structures

tree -if --noreport dir1 > dir1.txt
tree -if --noreport dir2 > dir2.txt
diff dir1.txt dir2.txt

This creates full-path listings without indentation for easy comparison.

Integration with Other Commands

Piping to grep

Find specific files in the tree output:

tree | grep "\.py
quot;

Combining with find

For more complex file searches:

tree -fi | grep -i "readme"

The -i option with tree removes indentation, making the output easier to parse.

Counting Files by Type

tree -fi | grep "\.js
quot; | wc -l

This counts all JavaScript files in the directory tree.

Configuration and Environment Variables

LS_COLORS

Tree uses the LS_COLORS environment variable for colorization when the -C option is used or when outputting to a terminal.

To customize colors, modify your LS_COLORS variable in your shell configuration:

export LS_COLORS='di=1;34:ln=1;36:ex=1;32'

TREE_CHARSET

The TREE_CHARSET environment variable can override character set settings for HTML mode.

.gitignore Integration

While tree doesn’t natively read .gitignore files, you can use similar exclusion patterns with the -I option to ignore files typically excluded from version control.

Performance Considerations

Large Directories

For directories with thousands of files:

  1. Use -L to limit depth
  2. Use --filelimit to skip huge directories
  3. Use -d to show only directories
  4. Use pattern matching to filter results

Example:

tree -L 3 --filelimit 500 -d

Network Filesystems

Be cautious when running tree on network-mounted filesystems, as it can generate significant network traffic. Use depth limiting and consider the -x option to stay within local filesystems.

Advantages Over Alternative Commands

Compared to ls -R

  • Visual hierarchy: Tree shows parent-child relationships clearly
  • Summary statistics: Automatic counts of files and directories
  • Depth control: Easy limitation of recursion depth
  • Better filtering: Pattern matching with -P and -I options

Compared to find

  • Readability: Visual tree structure vs. flat list
  • Simplicity: Less complex syntax for basic operations
  • Summary information: Built-in file and directory counts

Compared to du

  • File visibility: Shows individual files, not just sizes
  • Hierarchy: Clear parent-child relationships
  • Flexibility: Multiple output formats and filtering options

Common Use Cases

Software Development

  • Document project structure for README files
  • Audit dependency directories
  • Visualize source code organization
  • Identify orphaned or misplaced files

System Administration

  • Audit directory structures
  • Monitor log file organization
  • Document configuration hierarchies
  • Analyze disk usage patterns

Data Science

  • Organize dataset structures
  • Document model directories
  • Track experiment outputs
  • Audit data pipelines

Web Development

  • Visualize asset organization
  • Document API structures
  • Audit build outputs
  • Map content hierarchies

Tips and Best Practices


  1. Combine options: Many options work well together, such as tree -pughD for comprehensive file information.



  2. Use exclusions liberally: Exclude common clutter directories with -I "node_modules|.git|build|dist".



  3. Document projects: Include a tree output in your project’s README or documentation.



  4. Create aliases: Add commonly used tree commands to your shell aliases:


    alias treef='tree -L 3 --dirsfirst -I "node_modules|.git"'


  5. Export for sharing: Generate HTML or JSON output for sharing with others or integration with tools.



  6. Respect privacy: Be careful not to expose sensitive directory structures when sharing tree output.



  7. Use depth limits: Always use -L when exploring unfamiliar directories to prevent overwhelming output.


Troubleshooting

Unicode Issues

If you see garbled characters instead of tree lines, try:

tree -A  # Use ASCII characters

Or check your terminal’s character encoding settings (UTF-8 recommended).

Permission Denied Errors

When accessing restricted directories:

sudo tree /restricted/directory

Or filter out permission errors:

tree 2>/dev/null

Too Much Output

If tree generates overwhelming output:

  • Use -L to limit depth
  • Pipe through less: tree | less
  • Redirect to a file: tree > output.txt
  • Use --filelimit to skip large directories

Conclusion

The tree command is an essential tool for anyone working with Linux and Unix-like systems. Its ability to visualize directory structures quickly and clearly makes it invaluable for documentation, debugging, and understanding complex file hierarchies. With its extensive options for filtering, formatting, and output control, tree can be adapted to virtually any directory listing need.

Whether you’re a system administrator documenting server configurations, a developer mapping project structures, or a data scientist organizing datasets, mastering the tree command will significantly improve your workflow efficiency.

Additional Resources

  • Manual page: man tree
  • Help output: tree --help
  • Version information: tree --version
  • Source code and development: The tree command is open source and available for examination and contribution

By combining tree with other Unix tools and incorporating it into your daily workflow, you’ll gain a powerful ally in managing and understanding filesystem structures.