DEV Community

Query Filter
Query Filter

Posted on

print tree2

!/usr/bin/env bash

Unicode-style tree with file sizes and total files per directory

print_tree() {
local dir="$1"
local prefix="${2:-}"
local maxdepth="${3:-0}" # 0 = unlimited
local depth="${4:-1}"

# Exit if maxdepth reached
if [[ $maxdepth -ne 0 && $depth -gt $maxdepth ]]; then
    return
fi

# Ensure directory exists
[[ ! -d "$dir" ]] && return

echo "${prefix}${dir##*/}/"

# Enable nullglob so empty dirs don't break loops
shopt -s nullglob

# Get directories first
local dirs=("$dir"/*/)
IFS=$'\n' dirs=($(sort <<<"${dirs[*]}"))

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

# Then files
local files=("$dir"/*)
IFS=$'\n' files=($(sort <<<"${files[*]}"))
local file_count=0
for f in "${files[@]}"; do
    [[ -f "$f" ]] || continue
    local branch="├──"
    [[ $file_count -eq $(( ${#files[@]} - 1 )) ]] && branch="└──"
    # Human-readable size
    local size=$(stat -c "%s" "$f" 2>/dev/null || stat -f "%z" "$f")
    local hr_size
    if [[ "$size" =~ ^[0-9]+$ ]]; then
        if [ "$size" -lt 1024 ]; then
            hr_size="${size}B"
        elif [ "$size" -lt $((1024*1024)) ]; then
            hr_size="$((size/1024))K"
        elif [ "$size" -lt $((1024*1024*1024)) ]; then
            hr_size="$((size/1024/1024))M"
        else
            hr_size="$((size/1024/1024/1024))G"
        fi
    else
        hr_size="?"
    fi
    echo "${prefix}${branch} ${f##*/} [${hr_size}]"
    ((file_count++))
done

# Total files in directory
if [ $file_count -gt 0 ]; then
    echo "${prefix}└── Total files: $file_count"
fi

shopt -u nullglob
Enter fullscreen mode Exit fullscreen mode

}

Usage: print_tree

Example: print_tree . "" 0 # unlimited depth

print_tree . "" 0

Top comments (0)