DEV Community

Siswoyo Siswoyo
Siswoyo Siswoyo

Posted on

The `tree` Command in Ubuntu

πŸ“Œ Introduction

The tree command in Ubuntu is a powerful utility that displays the contents of directories in a tree-like structure. Instead of listing files and directories in a flat list (like ls does), it visually represents the hierarchy of directories, making it easier to understand the structure of a file system.

This is especially useful for:

  • Viewing project structures
  • Exploring configuration files
  • Understanding nested directories at a glance

πŸ“₯ Installation

By default, tree may not be installed on Ubuntu. You can install it using:

sudo apt update
sudo apt install tree -y
Enter fullscreen mode Exit fullscreen mode

To confirm installation:

tree --version
Enter fullscreen mode Exit fullscreen mode

πŸ“‚ Basic Usage

1. Display current directory structure

   tree
Enter fullscreen mode Exit fullscreen mode

2. Show full path of files and directories

   tree -f
Enter fullscreen mode Exit fullscreen mode

3. Limit depth of directory tree

   tree -L 2
Enter fullscreen mode Exit fullscreen mode

(This shows only two levels deep.)

4. Show hidden files (dotfiles)

   tree -a
Enter fullscreen mode Exit fullscreen mode

5. Print size of files

   tree -s
Enter fullscreen mode Exit fullscreen mode

🎯 Common Options

Option Description
-a Show all files including hidden ones
-d List directories only
-L n Limit depth of directory tree to n levels
-f Print full path for each file
-s Show file size in bytes
-h Show file size in human-readable format
--du Show cumulative directory sizes
-P List only files matching a pattern
-I Exclude files matching a pattern

πŸ” Examples

1. Display only directories up to 3 levels

   tree -d -L 3
Enter fullscreen mode Exit fullscreen mode

2. Show file sizes in human-readable format

   tree -h
Enter fullscreen mode Exit fullscreen mode

3. Exclude specific directories (e.g., .git)

   tree -I ".git"
Enter fullscreen mode Exit fullscreen mode

4. Display project structure

   tree -L 2 -I "node_modules"
Enter fullscreen mode Exit fullscreen mode

πŸ“‘ Example Output

If you run tree -L 2 inside a project folder, you may get:

.
β”œβ”€β”€ README.md
β”œβ”€β”€ package.json
β”œβ”€β”€ public
β”‚   β”œβ”€β”€ index.html
β”‚   └── favicon.ico
└── src
    β”œβ”€β”€ App.js
    β”œβ”€β”€ index.js
    └── components
Enter fullscreen mode Exit fullscreen mode

βœ… Conclusion

The tree command in Ubuntu is an essential tool for visualizing directory structures. With its various options, it allows developers, system administrators, and everyday users to quickly understand and navigate complex file systems.

Reference: https://manpages.ubuntu.com/manpages/jammy/man1/tree.1.html

Top comments (0)