如何统计Git特定分支的文件数量并列出文件?
获取Git特定分支的文件清单与数量
1. 列出所有文件清单
直接用git ls-tree命令就能查看目标分支最新状态下的所有文件,递归遍历的命令如下:
git ls-tree -r --name-only <分支名>
参数说明:
-r:递归遍历所有子目录,不会漏掉嵌套文件--name-only:只输出文件路径,不显示Git内部的元数据信息
比如查询master分支的文件,执行:
git ls-tree -r --name-only master
输出为清晰的文件路径列表:
components/abc.html components/def.html components/ghi.html static/main.js static/style.css index.html
2. 统计文件总数
在上述命令基础上,结合系统自带的计数工具就能算出文件总数:
Linux/macOS 环境
git ls-tree -r --name-only <分支名> | wc -l
Windows CMD 环境
git ls-tree -r --name-only <分支名> | find /c /v ""
Windows PowerShell 环境
(git ls-tree -r --name-only <分支名>).Count
3. 生成树形结构的文件清单
如果想要生成你示例里那种层级分明的树形展示,需要借助系统的tree命令(Linux/macOS一般自带,Windows可通过WSL或单独安装tree工具实现):
- 先将分支的文件列表导出到临时文件:
git ls-tree -r --name-only master > filelist.txt
- 用tree命令读取文件并生成树形结构:
tree --fromfile filelist.txt
输出效果会和你提供的示例类似,自动整理目录与文件的层级关系。
内容的提问来源于stack exchange,提问作者mhhabib
相关产品推荐
相关产品推荐

