9 tree Command Examples to Explore Linux Directories Like a Pro

Tree Command Examples

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

  1. Display the Directory Structure
  2. Show Hidden Files as Well
  3. Limit Depth to a Specific Level
  4. Display Only Directories
  5. Print Full Path of Each File
  6. Sort Files Alphabetically with Directories First
  7. Ignore Specific Directories
  8. Display Tree for a Specific Directory
  9. Combine Options for Better Output

1. Display the Directory Structure

tree

This command prints the structure of the current directory and its subdirectories.

Tree Command

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.

Tree Limit Depth

4. Display Only Directories

tree -d

Use this option to list only directories and ignore files.

Tree Display Directories

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.

Tree print full path

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.

Related Posts

Leave a Reply