tree 以 ASCII/Unicode 字符繪製樹狀圖展示目錄結構,比 ls -R 更直觀,支持深度限制、模式過濾、輸出重定向,是文檔項目結構、遞交代碼審查的利器。本文以 Ubuntu 為例演示安裝與核心用法。
# Ubuntu / Debian / Mint
sudo apt-get update && sudo apt-get install tree
# CentOS / RHEL / Fedora
sudo yum install tree
# 或 sudo dnf install tree
# Arch / Manjaro
sudo pacman -S tree

| 參數 | 功能 | 示例 |
|---|---|---|
-L <N> | 最大顯示深度 N 級 | tree -L 2 只顯示前兩級 |
-d | 僅顯示目錄,不顯示文件 | tree -d |
-a | 顯示隱藏文件 (以 . 開頭) | tree -a |
-I <pattern> | 排除匹配模式的文件/目錄 | tree -I 'node_modules|*.log' |
-P <pattern> | 僅顯示匹配模式的文件/目錄 | tree -P '*.py' |
| 顯示完整相對路徑前綴 | tree -f | |
| 文件大小人類可讀格式 (K/M/G) | tree -h | |
| 顯示文件大小 (字節) | tree -s | |
| 顯示文件擁有者 | tree -u | |
| 顯示文件所屬組 | tree -g | |
| 顯示最後修改時間 | tree -D | |
| 不顯示最後統計報告 | tree --noreport | |
| 輸出到文件 (等同重定向) | tree -o dir.txt | |
| 指定繪圖字符集 | tree --charset=ascii |
tree

tree -L 1 # 僅當前目錄
tree -L 2 # 當前 + 一級子目錄
tree -L 3 # 三級

# 導出前兩級結構到文件
tree -L 2 > /home/user/project_structure.txt
# 或使用 -o 參數
tree -L 2 -o /home/user/project_structure.txt

cat /home/user/project_structure.txt

# 專案結構文檔:顯示目錄、隱藏文件、前兩級、排除 node_modules/.git、人類可讀大小
tree -a -L 2 -I 'node_modules|.git|__pycache__|*.pyc|*.log' -h --noreport -o structure.md
# 生成 Markdown 代碼塊 (便於文檔嵌入)
echo '```' > structure.md && tree -a -L 3 -I 'node_modules|.git' >> structure.md && echo '```' >> structure.md
tree --help
man tree

tree 遞歸遍歷大目錄 (如 node_modules) 極慢,務必用 -I 排除cat -A 可見,建議加 --noreport 或管道 sed 's/\x1b\[[0-9;]*m//g' 去色tree.com (系統自帶) 或 Git Bash 附帶的 treetree -L N 控制深度、-I 排除噪音、-o/> 導出文本,三招覆蓋 90% 文檔化目錄結構需求。配合 git ls-files 或 find 可實現更精準的項目結構提取。