738

Is there any linux command that I can call from a Bash script that will print the directory structure in the form of a tree, e.g.,

folder1
   a.txt
   b.txt
folder2
   folder3
7
  • 19
    Just run find. Or find . -not -path '*/\.*' to hide files and folders starting with .. If you want to have output with spaces, as in the question, use it with this "find prettifier" script: find . -not -path '*/\.*' | python -c "import sys as s;s.a=[];[setattr(s,'a',list(filter(lambda p: c.startswith(p+'/'),s.a)))or (s.stdout.write(' '*len(s.a)+c[len(s.a[-1])+1 if s.a else 0:])or True) and s.a.append(c[:-1]) for c in s.stdin]"
    – user
    Commented Jun 14, 2014 at 0:49
  • 15
    Shouldn't such questions get migrated to SuperUser rather than closed ?
    – Balmipour
    Commented Oct 10, 2015 at 10:34
  • 16
    i dont think this question deserves to be closed as "off topic". The tags seem to be right. Commented Dec 1, 2015 at 8:27
  • 29
    The policy of closing questions without migrating is harmful to both stackoverflow and human knowledge in general. In the last 3 days, every single questions I googled and came across was closed for similar reasoning, and no more activity was able to happen. This means no one can update it, no one can give a better answer, and it makes stackoverflow look shortsighted or elitist. Stackoverflow should consider requiring a migration when a topic is found to have these conditions.
    – Nay
    Commented Nov 27, 2016 at 19:32
  • 6
    I agree with @NickYeates I am here in late September of 2017 still finding answers to this same question. Think long term when we design these question and answer policies!
    – Alex
    Commented Sep 28, 2017 at 20:38

15 Answers 15

1044

Is this what you're looking for tree? It should be in most distributions (maybe as an optional install).

~> tree -d /proc/self/
/proc/self/
|-- attr
|-- cwd -> /proc
|-- fd
|   `-- 3 -> /proc/15589/fd
|-- fdinfo
|-- net
|   |-- dev_snmp6
|   |-- netfilter
|   |-- rpc
|   |   |-- auth.rpcsec.context
|   |   |-- auth.rpcsec.init
|   |   |-- auth.unix.gid
|   |   |-- auth.unix.ip
|   |   |-- nfs4.idtoname
|   |   |-- nfs4.nametoid
|   |   |-- nfsd.export
|   |   `-- nfsd.fh
|   `-- stat
|-- root -> /
`-- task
    `-- 15589
        |-- attr
        |-- cwd -> /proc
        |-- fd
        | `-- 3 -> /proc/15589/task/15589/fd
        |-- fdinfo
        `-- root -> /

27 directories

sample taken from maintainer's web page.

You can add the option -L # where # is replaced by a number, to specify the max recursion depth.

Remove -d to display also files.

18
  • 84
    Note for any visitor seeing this: remove -d to display files also!
    – q9f
    Commented May 11, 2013 at 8:49
  • 40
    Note for any visitor seeing this: The man page lists a truckload of more flags for you :)
    – oivvio
    Commented Apr 26, 2014 at 18:52
  • 67
    To install on Mac OS X w/Homebrew: brew install tree
    – funfuntime
    Commented Dec 23, 2014 at 8:48
  • 2
    To install on cygwin apt-cyg install tree (assuming you've installed apt-cyg)
    – blockloop
    Commented Feb 19, 2015 at 19:36
  • 8
    Not even Ubuntu 16.04 comes with this. Use apt-get install tree will install it. Commented Sep 6, 2017 at 9:52
481

You can use this one:

ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/   /' -e 's/-/|/'

It will show a graphical representation of the current sub-directories without files in a few seconds, e.g. in /var/cache/:

   .
   |-apache2
   |---mod_cache_disk
   |-apparmor
   |-apt
   |---archives
   |-----partial
   |-apt-xapian-index
   |---index.1
   |-dbconfig-common
   |---backups
   |-debconf

Source

10
  • 13
    If you want it with spaces, more like the OP requested, then this: ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\// /g' -e 's/^/ /'
    – Ben
    Commented Oct 4, 2013 at 0:56
  • any way I can make this ignore dotfiles? E.g. prevent it from listing the contents of .git?
    – GMA
    Commented Apr 25, 2014 at 6:31
  • 1
    @GeorgeMillo see my comment
    – user
    Commented Jun 14, 2014 at 0:55
  • 122
    with files: find . | sed -e "s/[^-][^\/]*\// |/g" -e "s/|\([^ ]\)/|-\1/" Commented Jun 29, 2018 at 19:31
  • 3
    @Ben thanks for that, all other (non-tree) answers produce a result that does not look perfectly correct to me. For example in this answer, there should be a line going down from apt then horizontally to archives, instead it comes down from . and goes to archives, only because of more indentation you can guess that it's actually a subfolder of apt. So you could as well just leave the lines away, it's at least not misleading then.
    – msa
    Commented Nov 6, 2020 at 11:07
103

This command works to display both folders and files.

find . | sed -e "s/[^-][^\/]*\// |/g" -e "s/|\([^ ]\)/|-\1/"

Example output:

.
 |-trace.pcap
 |-parent
 | |-chdir1
 | | |-file1.txt
 | |-chdir2
 | | |-file2.txt
 | | |-file3.sh
 |-tmp
 | |-json-c-0.11-4.el7_0.x86_64.rpm

Source: Comment from @javasheriff here. Its submerged as a comment and posting it as answer helps users spot it easily.

5
  • 2
    for python3 I found find . |grep -vE 'pyc|swp|__init' | sed -e "s/[^-][^\/]*\// |/g" -e "s/|\([^ ]\)/|-\1/" working well Commented May 20, 2020 at 9:55
  • 2
    This was a great help as we didn't have tree installed on a certain server. This will most likely work on any standard Linux system.
    – jaw
    Commented Jan 7, 2022 at 7:11
  • Thanks. How can we make the results in alphabetical order?
    – laviex
    Commented Dec 5, 2022 at 14:49
  • @lavlex you can order the top-level directories with find * | sed ... but that's as far as I'm willing to think at the moment.
    – FlipMcF
    Commented Aug 24, 2023 at 19:54
  • Hi, is there a way to get the number of files in every directory as well?
    – AMDP
    Commented Dec 11, 2023 at 9:24
57

Since it was a successful comment, I am adding it as an answer:
To print the directory structure in the form of a tree,
WITH FILES

 find . | sed -e "s/[^-][^\/]*\//  |/g" -e "s/|\([^ ]\)/|-\1/" 
2
  • 6
    If you would like to sort your result list then combine the nice solution above with sort this way: find . | sort | sed -e "s/[^-][^\/]*\// |/g" -e "s/|\([^ ]\)/|-\1/"
    – zappee
    Commented Oct 14, 2021 at 13:18
  • 2
    @zappee sort can show incorrect structure, the folder and file with almost same name example build.gradle.kts (file) and build (a folder with child folder named generated) will be switched thus what you end up seeing in the terminal is a file having a child folder. Commented Apr 2 at 15:14
31

Since I was not too happy with the output of other (non-tree) answers (see my comment at Hassou's answer), I tried to mimic trees output a bit more.

It's similar to the answer of Robert but the horizontal lines do not all start at the beginning, but where there are supposed to start. Had to use perl though, but in my case, on the system where I don't have tree, perl is available.

ls -aR | grep ":$" | perl -pe 's/:$//;s/[^-][^\/]*\//    /g;s/^    (\S)/└── \1/;s/(^    |    (?= ))/│   /g;s/    (\S)/└── \1/'

Output (shortened):

.
└── fd
└── net
│   └── dev_snmp6
│   └── nfsfs
│   └── rpc
│   │   └── auth.unix.ip
│   └── stat
│   └── vlan
└── ns
└── task
│   └── 1310
│   │   └── net
│   │   │   └── dev_snmp6
│   │   │   └── rpc
│   │   │   │   └── auth.unix.gid
│   │   │   │   └── auth.unix.ip
│   │   │   └── stat
│   │   │   └── vlan
│   │   └── ns

Suggestions to avoid the superfluous vertical lines are welcome :-)

I still like Ben's solution in the comment of Hassou's answer very much, without the (not perfectly correct) lines it's much cleaner. For my use case I additionally removed the global indentation and added the option to also ls hidden files, like so:

ls -aR | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//  /g'

Output (shortened even more):

.
  fd
  net
    dev_snmp6
    nfsfs
    rpc
      auth.unix.ip
    stat
    vlan
  ns
1
  • The only way to get rid of the unwanted vertical lines when processing the output of ls -R is to proceed from last to first line. See the awk-based solution I provided, which you could easily adapt to perl. Commented Oct 9, 2021 at 20:26
21

To add Hassou's solution to your .bashrc, try:

alias lst='ls -R | grep ":$" | sed -e '"'"'s/:$//'"'"' -e '"'"'s/[^-][^\/]*\//--/g'"'"' -e '"'"'s/^/   /'"'"' -e '"'"'s/-/|/'"'"
2
  • 6
    Beware of the newline character at the end of the first line if copying this directly
    – Rahul
    Commented Aug 5, 2016 at 16:46
  • 3
    Nice alias. But there is missing ' ' (2 single quote chars) at the end. It works even without it, but... if you want to add some more commands at the end you will see the literal is not complete. So it should go alias lst='ls -R | grep ":$" | sed -e '"'"'s/:$//'"'"' -e '"'"'s/[^-][^\/]*\//--/g'"'"' -e '"'"'s/^/ /'"'"' -e '"'"'s/-/|/'"'"''
    – Hero Qu
    Commented Feb 15, 2019 at 19:00
12

The best answer is, of course, tree. But, to improve on other answers that rely on grepping the output of ls -R, here is a shell script that uses awk to print a tree of subdirectories. First, an example of output:

.
└── matching
    ├── bib
    ├── data
    │   └── source
    │       └── html
    ├── data
    │   └── plots
    ├── method
    │   ├── info
    │   └── soft
    │       ├── imgs
    │       │   ├── ascii
    │       │   └── symbol
    │       └── js
    └── ms

Then, the code:

ls -qLR 2>/dev/null \
| grep '^./' \
| sed -e 's,:$,,' \
| awk '
    function tip(new) { stem = substr(stem, 1, length(stem) - 4) new }
    {
        path[NR] = $0
    }
    END {
        elbow = "└── "; pipe = "│   "; tee = "├── "; blank = "    "
        none = ""
        #
        # Model each stem on the previous one, going bottom up.
        for (row = NR; row > 0; row--) {
            #
            # gsub: count (and clean) all slash-ending components; hence,
            # reduce path to its last component.
            growth = gsub(/[^/]+\//, "", path[row]) - slashes
            if (growth == 0) {
                tip(tee)
            }
            else if (growth > 0) {
                if (stem) tip(pipe) # if...: stem is empty at first!
                for (d = 1; d < growth; d++) stem = stem blank
                stem = stem elbow
            }
            else {
                tip(none)
                below = substr(stem, length(stem) - 4, 4)
                if (below == blank) tip(elbow); else tip(tee)
            }
            path[row] = stem path[row]
            slashes += growth
        }
        root = "."; print root
        for (row = 1; row <= NR; row++) print path[row]
    }
'

The code gives better-looking results than other solutions because in a tree of subdirectories, the decorations in any branch depend on the branches below it. Hence, we need to process the output of ls -R in reverse order, from the last line to the first.

2
  • What system did you test it on? I get an error awk: nonterminated character class [^ on gsub line on Mac.
    – Andy
    Commented Jan 4, 2023 at 21:25
  • @Andrei I tested it on Arch, where awk is symlinked to gawk (= GNU awk). So this may be another pesky awk/gawk difference. Perhaps you should escape the slash inside the character class: /[^\/]+\// Commented Jan 6, 2023 at 14:34
9

I'm prettifying the output of @Hassou's answer with:

ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//──/g' -e 's/─/├/' -e '$s/├/└/'

This is much like the output of tree now:

.
├─pkcs11
├─pki
├───ca-trust
├─────extracted
├───────java
├───────openssl
├───────pem
├─────source
├───────anchors
├─profile.d
└─ssh

You can also make an alias of it:

alias ltree=$'ls -R | grep ":$" | sed -e \'s/:$//\' -e \'s/[^-][^\/]*\//──/g\' -e \'s/─/├/\' -e \'$s/├/└/\''

BTW, tree is not available in some environment, like MinGW. So the alternate is helpful.

2
  • gitbash on windows does not like the last expression, it says that it is not terminated Commented Apr 22, 2020 at 10:51
  • 2
    @LeosLiterak: On Windows, native tree should be available with Command Prompt (cmd) or PowerShell though :-)
    – msa
    Commented Nov 6, 2020 at 10:43
7

Combining and extending existing answers into t shell function

t() {
  find -E "${1:-.}" -maxdepth "${2:-3}" \
    -not -regex ".*\/((.idea|.git|.venv|node_modules|venv)\/.*|.DS_Store)" \
  | sort | sed \
    -e "s/[^-][^\/]*\// ├ /g" \
    -e "s/├ \//├ /g" \
    -e "s/├  ├/│  ├/g" \
    -e "s/├  ├/│  ├/g" \
    -e "s/├  │/│  │/g" \
    -e '$s/├/└/'
}

Works on Mac:

$ t
.
 ├ src
 │  ├ .idea
 │  ├ plugins
 │  │  ├ .flake8
 │  │  ├ .git
 │  │  ├ .github
 │  │  ├ .gitignore
 │  │  ├ .pre-commit-config.yaml
 │  │  ├ .python-version
 │  │  ├ Makefile
 │  │  ├ README.md
 │  │  ├ buildspecs
 │  │  ├ cicd
 │  │  ├ cicd.py
 │  │  ├ docker
 │  │  ├ packages
 │  │  ├ plugin_template
 │  │  ├ plugins
 │  │  ├ scripts
 │  │  └ venv


$ t . 2
.
 ├ src
 │  ├ .idea
 │  └ plugins


$ t src/plugins/ | more
 │  ├
 │  ├ .flake8
 │  ├ .git
 │  ├ .github
 │  │  ├ pull_request_template.md
 │  ├ .gitignore
 │  ├ .pre-commit-config.yaml
 │  ├ .python-version
 │  ├ Makefile
 │  ├ README.md
 │  ├ buildspecs
 │  │  ├ test-and-deploy.yml
 │  ├ cicd
:

| more can be put at the end of the function for convenience.

2
  • 3
    Nice solution to copy paste to your .bashrc. On Linux (Debian 11) omit the -E option passed to find.
    – jammartin
    Commented Oct 12, 2023 at 13:59
  • 1
    this is a gem <3 Commented Nov 7, 2023 at 19:55
6

Adding the below function in bashrc lets you run the command without any arguments which displays the current directory structure and when run with any path as argument, will display the directory structure of that path. This avoids the need to switch to a particular directory before running the command.

function tree() {
    find ${1:-.} | sed -e "s/[^-][^\/]*\//  |/g" -e "s/|\([^ ]\)/|-\1/"
}

This works in gitbash too.

Source: Comment from @javasheriff here

4

You can also use the combination of find and awk commands to print the directory tree. For details, please refer to "How to print a multilevel tree directory structure using the linux find and awk combined commands"

find . -type d | awk -F'/' '{ 
depth=3;
offset=2;
str="|  ";
path="";
if(NF >= 2 && NF < depth + offset) {
    while(offset < NF) {
        path = path "|  ";
        offset ++;
    }
    print path "|-- "$NF;
}}'
1

We can use below command

tree

This will return tree like structure.

If you want entire directory till the end subdirectory. You need to fire below command.

find . -type d

0

Expanding on msa's perl version I've tossed in a bit of ANSI color coding output matching default ls --color choices. I also added files back into the listing. Wrapped in a bash function for use in ~/.bashrc and formatted with commentary, it now looks like this:

function tree() {
    find ${1:-.} | perl -pe '
        chomp();                        # Lose the line ending for file tests
        $f=$_;                          # Keep full path in $f for file tests
        if(-d $f)     { $c="\e[0;34m" } # Directories BLUE
        elsif (-l $f) { $c="\e[0;36m" } # Links CYAN
        elsif (-X $f) { $c="\e[0;32m" } # Executables GREEN
        else          { $c="\e[0m" }    # Else just RESET
        s/[^-][^\/]*\//  |/g;           # Get rid of ./our/leading/path to just "  |path"
        s/\|([^ ]+)/└──$c$1\e[0m/;      # Change |path to └──path and add $c coloring with reset
        if (-d $f) {                    # If directory add trailing / too
            s/$/\//
        };
        print("\n");                    # Because we chomp()ed the ending off at the start
        END { print("\n"); }'           # One last line ending to keep it clean
}

I prefer perl for these kinds of shenanigans because: Perl makes it easier to deal with the file tests and ANSI escape sequences than sed. Love it or hate it Perl is base install for nearly every Unix style OS. I love Python, but it's useless for "one liners" like this that I want to throw in my ~/.bashrc tools pile. The tree command is great, but again it isn't often installed and I find it easier to carry a bunch of magic spells in my ~/.bashrc spell book when working across random systems.

0

After two hours and a lot of trial and error because I'm not very good with sed or perl.

Anyway, here's my output:

Makefile

ARGUMENTS := $(filter-out --,$(filter-out $(firstword $(MAKECMDGOALS)),$(MAKECMDGOALS)))
FIRST_ARGUMENT := $(word 1, $(ARGUMENTS))
SECOND_ARGUMENT := $(word 2, $(ARGUMENTS))

ifeq (tree, $(firstword $(MAKECMDGOALS)))
  # use the rest as arguments for "run"
  RUN_ARGS := $(wordlist 2,$(words $(MAKECMDGOALS)),$(MAKECMDGOALS))
  # ...and turn them into do-nothing targets
  $(eval $(RUN_ARGS):;@:)
endif

# Tree command
tree:
    @if [ "${FIRST_ARGUMENT}" = "dir" ]; then \
        ls -aR ./${SECOND_ARGUMENT} | grep ":$$" | \
        perl -pe 's/:$$//;s/[^-][^\/]*\//    /g;s/^    (\S)/ └─── \1/;s/(^     |    (?= ))/ │   /g;s/     (\S)/   └─── \1/'; \
    elif [ "${FIRST_ARGUMENT}" = "file" ]; then  \
        find ./${SECOND_ARGUMENT} | sed -e "s/[^-][^\/]*\// │   /g" -e "s/│   \([^  ]\)/└─── \1/"; \
    else \
        exit 1; \
    fi;

The following commands can be useful:

make tree dir source

It means print a tree consisting only of directories starting from the ./source directory.

Output:

> make tree dir source
 └─── source
 │    └─── bin
 │    │    └─── gcd
 │    │    └─── primetest
 │    └─── libs
 │    │    └─── GCDUtilities
 │    │    └─── PrimalityUtilities
make: 'source' is up to date.

make tree file source

This command would print all the files residing under ./source directory as a tree.

> make tree file source
 └─── source
 │    └─── bin
 │    │    └─── gcd
 │    │    │    └─── main.c
 │    │    └─── primetest
 │    │    │    └─── main.c
 │    └─── libs
 │    │    └─── GCDUtilities
 │    │    │    └─── gcd.c
 │    │    └─── PrimalityUtilities
 │    │    │    └─── isprime.c
make: 'source' is up to date.
0

The tree command is your best option.


Alternative

If you are not a sudoer user or cannot install tree, you can use a bash script that utilizes the file and stat commands.

I tried to stick as close to the tree command's options as much as possible.

I even added highlighting for archives, links, and executables.

#!/usr/bin/env bash
#==============================================================================
# TITLE          : tree
# DESCRIPTION    : A clone of the tree utility with additional features.
# AUTHOR         : Mr. Polywhirl
# DATE           : 2024-07-24
# VERSION        : 1.0.0
# USAGE          : tree [OPTIONS] [directory]
# NOTES          : Requires the 'file' and 'stat' commands.
# BASH_VERSION   : 4.2.46(2)-release
#==============================================================================
# DESCRIPTION:
# A clone of the tree utility with additional features such as 
# displaying file sizes, sorting directories before files, and color highlighting.
#------------------------------------------------------------------------------
# USAGE:
#   tree [OPTIONS] [directory]
#------------------------------------------------------------------------------
# OPTIONS:
#   -s          Print the size of each file in bytes.
#   -h          Print the size of each file in a human-readable way
#               (e.g., appending a size letter for kilobytes (K), megabytes (M),
#               gigabytes (G), terabytes (T), petabytes (P), and exabytes (E)).
#   -L level    Max display depth of the directory tree.
#   -o file     Send output to the specified file.
#   --dirsfirst List directories before files.
#   --help      Display this help message.
#------------------------------------------------------------------------------
# EXAMPLES:
#   Print the tree with file sizes in bytes:
#       tree -s /path/to/directory
#
#   Print the tree with file sizes in a human-readable way:
#       tree -h /path/to/directory
#
#   Print the tree with a maximum depth of 2:
#       tree -L 2 /path/to/directory
#
#   Print the tree with directories listed before files:
#       tree --dirsfirst /path/to/directory
#------------------------------------------------------------------------------
# INSTALLATION:
#   1. Save this script to a file named '~/.scripts/tree'.
#   2. Make the script executable with the command 'chmod u+x ~/.scripts/tree'.
#   3. Add the directory '~/.scripts' to your PATH environment variable.
#==============================================================================

# Define ANSI color codes
RESET='\033[0m'
RED='\033[0;91m'
GREEN='\033[0;92m'
BLUE='\033[1;94m'
CYAN='\033[1;96m'

# Define a list of MIME types for compressed archives
ARCHIVE_MIME_TYPES=(
    "application/zip"                                # .zip
    "application/x-tar"                              # .tar
    "application/gzip"                               # .gz
    "application/x-bzip2"                            # .bz2
    "application/x-xz"                               # .xz
    "application/x-7z-compressed"                    # .7z
    "application/x-rar"                              # .rar
    "application/java-archive"                       # .jar
    "application/x-archive"                          # .ar
    "application/vnd.android.package-archive"        # .apk
    "application/vnd.debian.binary-package"          # .deb
    "application/x-redhat-package-manager"           # .rpm
    "application/vnd.microsoft.portable-executable"  # .exe
    "application/vnd.ms-cab-compressed"              # .cab
)

# Default values for options
print_size=false
max_depth=-1
human_readable_size=false
output_file=""
use_color=true
dirs_first=false

highlight() {
    local name=$1
    local color=$2
    if $use_color; then
        echo -e "${color}${name}${RESET}"
    else
        echo "$name"
    fi
}

highlight_link() {
    local name=$1
    local target=$2
    if $use_color; then
        echo -e "${CYAN}${name}${RESET} -> $(highlight_item "$target")"
    else
        echo "$name -> $target"
    fi
}

highlight_item() {
    local item=$1
    local display_name

    display_name=$(basename "$item")

    if [ -d "$item" ]; then
        highlight "$display_name" "$BLUE"
    elif [ -x "$item" ]; then
        highlight "$display_name" "$GREEN"
    elif is_archive "$item"; then
        highlight "$display_name" "$RED"
    else
        echo "$display_name"
    fi
}

is_archive() {
    local item=$1
    local mime_type

    mime_type=$(file --mime-type -b "$item")
    for type in "${ARCHIVE_MIME_TYPES[@]}"; do
        if [[ "$mime_type" == "$type" ]]; then
            return 0
        fi
    done
    return 1
}

get_human_readable_size() {
    local size=$1
    local units=("B" "K" "M" "G" "T" "P" "E")
    local i=0

    while [ "$(echo "$size >= 1024" | bc)" -eq 1 ] && [ $i -lt ${#units[@]} ]; do
        size=$(echo "$size / 1024" | bc -l)
        size=$(printf "%.0f" "$size")  # Convert to integer for the next iteration
        i=$((i + 1))
    done

    printf "%.1f%s" "$size" "${units[$i]}"
}

get_size() {
    local item=$1
    local size

    size=$(stat -c%s "$item")
    if [ "$human_readable_size" = true ]; then
        echo " ($(get_human_readable_size "$size"))"
    else
        echo " ($size bytes)"
    fi
}

get_display_name() {
    local item=$1
    local display_name
    local size_info=""

    display_name=$(basename "$item")

    if [ "$print_size" = true ]; then
        size_info=$(get_size "$item")
    fi

    if [ -d "$item" ]; then
        display_name=$(highlight "$display_name" "$BLUE")
    elif [ -L "$item" ]; then
        local target
        target=$(readlink "$item")
        display_name=$(highlight_link "$display_name" "$target")
    else
        display_name=$(highlight_item "$item")
    fi

    echo "$display_name$size_info"
}

print_tree() {
    local dir=$1
    local prefix=$2
    local depth=$3
    local output=$4

    # Stop if max depth is reached
    if [ "$max_depth" -ne -1 ] && [ "$depth" -ge "$max_depth" ]; then
        return
    fi

    # List all files and directories in the current directory
    local items=("$dir"/*)

    # Handle empty directories
    if [ ! -e "${items[0]}" ]; then
        echo "${prefix}(empty)" >> "$output"
        return
    fi

    if $dirs_first; then
        # Separate directories and files
        local dirs=()
        local files=()
        for item in "${items[@]}"; do
            if [ -d "$item" ]; then
                dirs+=("$item")
            else
                files+=("$item")
            fi
        done
        items=("${dirs[@]}" "${files[@]}")
    fi

    local last_index=$((${#items[@]} - 1))

    for i in "${!items[@]}"; do
        local item="${items[$i]}"
        local new_prefix="${prefix}│   "

        # Determine the correct prefix for the next level
        if [ "$i" -eq $last_index ]; then
            new_prefix="${prefix}    "
        fi

        # Get the display name with colors
        local display_name
        display_name=$(get_display_name "$item")

        # Print the current item
        echo -e "${prefix}└── ${display_name}" >> "$output"

        # Recursively print the tree for directories
        if [ -d "$item" ]; then
            print_tree "$item" "$new_prefix" $((depth + 1)) "$output"
        fi
    done
}

print_help() {
    echo "Usage: $(basename "$0") [OPTIONS] [directory]"
    echo ""
    echo "Options:"
    echo "  -s          Print the size of each file in bytes"
    echo "  -h          Print the size of each file in a human-readable way"
    echo "              (e.g., appending a size letter for kilobytes (K), megabytes (M),"
    echo "              gigabytes (G), terabytes (T), petabytes (P), and exabytes (E))"
    echo "  -L level    Max display depth of the directory tree"
    echo "  -o file     Send output to the specified file"
    echo "  --dirsfirst List directories before files"
    echo "  --help      Display this help message"
}

# Parse options
while getopts "sho:L:-:" opt; do
    case $opt in
        s) print_size=true ;;
        h) print_size=true; human_readable_size=true ;;
        L) max_depth=$OPTARG ;;
        o) output_file=$OPTARG; use_color=false ;;
        -)
            case $OPTARG in
                help) print_help; exit 0 ;;
                dirsfirst) dirs_first=true ;;
                *) echo "Invalid option: --$OPTARG"; print_help; exit 1 ;;
            esac ;;
        *) echo "Invalid option: -$OPTARG"; print_help; exit 1 ;;
    esac
done
shift $((OPTIND - 1))

# Check if a directory is passed as an argument, otherwise use the current directory
if [ $# -eq 0 ]; then
    dir="."
else
    dir="$1"
fi

# Initialize the output file or standard output
if [ -n "$output_file" ]; then
    echo "." > "$output_file"
else
    output_file="/dev/stdout"
    echo "."
fi

# Start the tree printing
print_tree "$dir" "" 0 "$output_file"

Here is a simpler version, with no options or highlighting.

#!/usr/bin/env bash
#==============================================================================
# TITLE          : tree
# DESCRIPTION    : A simple clone of the tree utility.
# AUTHOR         : Mr. Polywhirl
# DATE           : 2024-07-24
# VERSION        : 1.0.0
# USAGE          : tree [directory]
# NOTES          : Requires bash version 4.2.46(2)-release or higher.
# BASH_VERSION   : 4.2.46(2)-release
#==============================================================================
# DESCRIPTION:
# A simple clone of the tree utility that prints the directory structure.
#------------------------------------------------------------------------------
# USAGE:
#   tree [directory]
#------------------------------------------------------------------------------
# EXAMPLES:
#   Print the tree structure for the current directory:
#       tree
#
#   Print the tree structure for a specified directory:
#       tree /path/to/directory
#==============================================================================
# INSTALLATION:
#   1. Save this script to a file named '~/.scripts/tree'.
#   2. Make the script executable with the command 'chmod u+x ~/.scripts/tree'.
#   3. Add the directory '~/.scripts' to your PATH environment variable.
#==============================================================================

print_tree() {
    local dir=$1
    local prefix=$2

    # List all files and directories in the current directory
    local items=("$dir"/*)
    local last_index=$((${#items[@]} - 1))

    for i in "${!items[@]}"; do
        local item="${items[$i]}"
        local new_prefix="${prefix}│   "

        # Determine the correct prefix for the next level
        if [ "$i" -eq $last_index ]; then
            new_prefix="${prefix}    "
        fi

        # Get the display name
        local display_name
        display_name=$(basename "$item")

        # Print the current item
        if [ -d "$item" ]; then
            echo "${prefix}└── ${display_name}/"
            # Recursively print the tree for directories
            if [ "$(ls -A "$item")" ]; then
                print_tree "$item" "$new_prefix"
            fi
        else
            echo "${prefix}└── ${display_name}"
        fi
    done
}

# Check if a directory is passed as an argument, otherwise use the current directory
if [ $# -eq 0 ]; then
    dir="."
else
    dir="$1"
fi

# Print the root directory
echo "."
# Start the tree printing
print_tree "$dir" ""

Not the answer you're looking for? Browse other questions tagged or ask your own question.