DEV Community

Query Filter
Query Filter

Posted on

print tree5

!/usr/bin/env bash

Fully working Linux Unicode tree with sizes and total files

print_tree() {
local dir="$1"
local prefix="${2:-}"

# Directories first
local dirs=()
while IFS= read -r d; do
    [[ -d "$d" && ! -L "$d" ]] && dirs+=("$d")
done < <(find "$dir" -mindepth 1 -maxdepth 1 -type d | sort)

local d_count=${#dirs[@]}
for i in "${!dirs[@]}"; do
    local d="${dirs[i]}"
    local branch="├──"
    [[ $i -eq $((d_count - 1)) ]] && branch="└──"
    local new_prefix="$prefix"
    [[ $i -eq $((d_count - 1)) ]] && new_prefix+="    " || new_prefix+="│   "
    echo "${prefix}${branch} ${d##*/}/"
    print_tree "$d" "$new_prefix"
done

# Files next
local files=()
while IFS= read -r f; do
    [[ -f "$f" ]] && files+=("$f")
done < <(find "$dir" -mindepth 1 -maxdepth 1 -type f | sort)

local f_count=${#files[@]}
for i in "${!files[@]}"; do
    local f="${files[i]}"
    local branch="├──"
    [[ $i -eq $((f_count - 1)) ]] && branch="└──"
    local size=$(stat -c "%s" "$f" 2>/dev/null || echo 0)
    local hr_size
    if [[ "$size" -lt 1024 ]]; then hr_size="${size}B"
    elif [[ "$size" -lt 1048576 ]]; then hr_size="$((size/1024))K"
    elif [[ "$size" -lt 1073741824 ]]; then hr_size="$((size/1024/1024))M"
    else hr_size="$((size/1024/1024/1024))G"; fi
    echo "${prefix}${branch} ${f##*/} [${hr_size}]"
done

[[ $f_count -gt 0 ]] && echo "${prefix}└── Total files: $f_count"
Enter fullscreen mode Exit fullscreen mode

}

Print root directory once

echo "${PWD##*/}/"
print_tree .

Top comments (0)