Shell脚本如何生成目录树结构

wen 实用脚本 6

本文目录导读:

Shell脚本如何生成目录树结构

  1. 使用 tree 命令(最简单)
  2. 使用 find 命令(兼容性更好)
  3. 自定义递归函数
  4. 带格式化的完整版本
  5. 简单实用的版本
  6. 使用方法
  7. 注意事项

使用 tree 命令(最简单)

#!/bin/bash
# 基本用法
tree
# 自定义深度
tree -L 2
# 只显示目录
tree -d
# 显示完整路径
tree -f
# 带文件大小
tree -h
# 输出到文件
tree > directory_tree.txt

使用 find 命令(兼容性更好)

#!/bin/bash
# 基本目录树
find . -type d | sort | while read dir; do
    depth=$(echo "$dir" | tr '/' '\n' | wc -l)
    indent=$(printf '%*s' $((depth * 2)) '')
    echo "${indent}├── $(basename "$dir")"
done
# 包含文件的版本
find . -print | sort | while read path; do
    depth=$(echo "$path" | tr '/' '\n' | wc -l)
    indent=$(printf '%*s' $((depth * 2)) '')
    if [ -d "$path" ]; then
        echo "${indent}├── 📁 $(basename "$path")"
    else
        echo "${indent}├── 📄 $(basename "$path")"
    fi
done

自定义递归函数

#!/bin/bash
# 递归打印目录树
print_tree() {
    local dir="$1"
    local prefix="$2"
    local depth="${3:-0}"
    local max_depth="${4:-5}"
    # 检查深度限制
    [ "$depth" -gt "$max_depth" ] && return
    # 获取目录内容
    local items=()
    while IFS= read -r item; do
        items+=("$item")
    done < <(ls -1 "$dir" 2>/dev/null)
    local count=${#items[@]}
    local i=0
    for item in "${items[@]}"; do
        ((i++))
        local path="$dir/$item"
        # 判断是否是最后一个项目
        if [ "$i" -eq "$count" ]; then
            echo "${prefix}└── $item"
            local new_prefix="${prefix}    "
        else
            echo "${prefix}├── $item"
            local new_prefix="${prefix}│   "
        fi
        # 如果是目录,递归处理
        if [ -d "$path" ]; then
            print_tree "$path" "$new_prefix" $((depth + 1)) "$max_depth"
        fi
    done
}
# 使用示例
echo "."
print_tree "." "" 0 3

带格式化的完整版本

#!/bin/bash
# 生成格式化的目录树
generate_tree() {
    local root="${1:-.}"
    local max_depth="${2:-5}"
    local current_depth=0
    # 颜色定义
    local COLOR_DIR='\033[1;34m'    # 蓝色
    local COLOR_FILE='\033[0;32m'   # 绿色
    local COLOR_RESET='\033[0m'
    print_node() {
        local path="$1"
        local prefix="$2"
        local depth="$3"
        [ "$depth" -gt "$max_depth" ] && return
        # 获取当前目录下的所有项目
        local items=()
        while IFS= read -r item; do
            items+=("$item")
        done < <(ls -1 "$path" 2>/dev/null | sort)
        local count=${#items[@]}
        local i=0
        for item in "${items[@]}"; do
            ((i++))
            local full_path="$path/$item"
            # 选择连接符
            if [ "$i" -eq "$count" ]; then
                echo -e "${prefix}└── ${COLOR_DIR}$item${COLOR_RESET}"
                local new_prefix="${prefix}    "
            else
                echo -e "${prefix}├── ${COLOR_DIR}$item${COLOR_RESET}"
                local new_prefix="${prefix}│   "
            fi
            # 如果是目录,递归
            if [ -d "$full_path" ]; then
                print_node "$full_path" "$new_prefix" $((depth + 1))
            fi
        done
    }
    echo "目录树: $root"
    echo "├── "
    print_node "$root" "" 0
}
# 使用
generate_tree "/path/to/directory" 3

简单实用的版本

#!/bin/bash
# 简单目录树函数
simple_tree() {
    find "${1:-.}" -type f -o -type d | sort | while read -r path; do
        depth=$(echo "$path" | tr '/' '\n' | wc -l)
        indent=$(printf '%*s' $((depth * 2)) '')
        name=$(basename "$path")
        if [ -d "$path" ]; then
            echo "${indent}[D] $name"
        else
            echo "${indent}[F] $name"
        fi
    done
}
# 使用
simple_tree
simple_tree /home/user/documents

使用方法

  1. 保存脚本为 tree-gen.sh
  2. 添加执行权限:chmod +x tree-gen.sh
  3. 运行:./tree-gen.sh

注意事项

  • tree 命令不可用,可以使用 apt install treebrew install tree 安装
  • 自定义版本更具可移植性,不依赖外部命令
  • 可以根据需要调整颜色、深度限制和输出格式
  • 对于大目录,建议设置深度限制避免输出过长

抱歉,评论功能暂时关闭!