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
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.
-d
to display files also!
apt-cyg install tree
(assuming you've installed apt-cyg)
Commented
Feb 19, 2015 at 19:36
apt-get install tree
will install it.
Commented
Sep 6, 2017 at 9:52
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
ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\// /g' -e 's/^/ /'
.git
?
find . | sed -e "s/[^-][^\/]*\// |/g" -e "s/|\([^ ]\)/|-\1/"
Commented
Jun 29, 2018 at 19:31
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.
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.
find . |grep -vE 'pyc|swp|__init' | sed -e "s/[^-][^\/]*\// |/g" -e "s/|\([^ ]\)/|-\1/"
working well
Commented
May 20, 2020 at 9:55
find * | sed ...
but that's as far as I'm willing to think at the moment.
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/"
sort
this way: find . | sort | sed -e "s/[^-][^\/]*\// |/g" -e "s/|\([^ ]\)/|-\1/"
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
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 tree
s 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
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
To add Hassou's solution to your .bashrc, try:
alias lst='ls -R | grep ":$" | sed -e '"'"'s/:$//'"'"' -e '"'"'s/[^-][^\/]*\//--/g'"'"' -e '"'"'s/^/ /'"'"' -e '"'"'s/-/|/'"'"
alias lst='ls -R | grep ":$" | sed -e '"'"'s/:$//'"'"' -e '"'"'s/[^-][^\/]*\//--/g'"'"' -e '"'"'s/^/ /'"'"' -e '"'"'s/-/|/'"'"''
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.
awk: nonterminated character class [^
on gsub line on Mac.
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.
tree
should be available with Command Prompt (cmd
) or PowerShell though :-)
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.
.bashrc
. On Linux (Debian 11) omit the -E
option passed to find
.
Commented
Oct 12, 2023 at 13:59
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
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;
}}'
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
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.
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.
The tree
command is your best option.
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" ""
find
. Orfind . -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]"