user
In Bash how to print sub-folders and files tree recursively in console?
alphonsio

Use the tree utility:

$ tree
.
├── base
│   ├── headings.css
│   └── typography.css
└── style.css

In Bash (or more generally, on Unix-like systems), the standard and most practical way to print a recursive directory and file tree in the console is to use the tree utility. If tree is not available, there are reliable alternatives using built-in tools.

Below are the primary approaches, from simplest to most portable.


1. Using tree (recommended)

Basic usage

tree

Print a specific directory

tree /path/to/directory

Include hidden files

tree -a

Limit recursion depth

tree -L 3

Show files only or directories only

tree -f      # full paths
tree -d      # directories only

If tree is not installed:

# Debian/Ubuntu
sudo apt install tree

# RHEL/CentOS
sudo yum install tree

# macOS
brew install tree

2. Using find (available everywhere)

Simple recursive listing

find .

Indented tree-style output

find . -print | sed -e 's;[^/]*/;|____;g'

This produces a visual hierarchy similar to tree, though without sorting or formatting options.

Files only

find . -type f

Directories only

find . -type d

3. Using ls recursively (not recommended for scripts)

ls -R

This prints all files recursively but lacks structure and is harder to read or parse.


4. Pure Bash function (no external dependencies)

tree_bash() {
  local dir="$1"
  local prefix="$2"

  for entry in "$dir"/*; do
    [ -e "$entry" ] || continue
    echo "${prefix}├── $(basename "$entry")"
    [ -d "$entry" ] && tree_bash "$entry" "│   $prefix"
  done
}

tree_bash .

This is useful in minimal environments where tree is unavailable.


Summary

MethodBest Use Case
treeHuman-readable directory trees
findPortability and scripting
ls -RQuick inspection
Bash functionDependency-free environments