You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Bash中统计Git仓库内容时排除.git目录及内部文件?

Git仓库三类内容统计Bash实现方案

命令逻辑说明

使用find命令的-prune参数实现剪枝,完全跳过.git目录及其内部所有内容,不需要额外过滤结果,执行效率更高。

单条统计命令

  • 统计所有子目录(含深层嵌套,不含.git相关目录)数量
    命令:find . -path ./.git -prune -o -type d -print | wc -l
  • 统计所有子目录下的.txt格式文件数量
    命令:find . -path ./.git -prune -o -type f -name "*.txt" -print | wc -l
  • 统计所有子目录下的非txt格式文件数量
    命令:find . -path ./.git -prune -o -type f ! -name "*.txt" -print | wc -l

整合脚本示例

将以下内容保存为stat_repo.sh,赋予执行权限后在Git仓库根目录运行即可一次性输出三个统计结果:

#!/bin/bash
# 排除.git目录统计三类资源数量
dir_count=$(find . -path ./.git -prune -o -type d -print | wc -l | tr -d ' ')
txt_count=$(find . -path ./.git -prune -o -type f -name "*.txt" -print | wc -l | tr -d ' ')
non_txt_count=$(find . -path ./.git -prune -o -type f ! -name "*.txt" -print | wc -l | tr -d ' ')

echo "===== 仓库资源统计结果 ====="
echo "子目录总数:$dir_count"
echo "txt格式文件总数:$txt_count"
echo "非txt格式文件总数:$non_txt_count"

注意事项

  • 所有命令默认在Git仓库根目录执行,若在其他路径执行,需将./.git替换为对应.git目录的相对/绝对路径
  • tr -d ' '用于去除wc -l输出结果前后的空白字符,避免输出格式异常
  • 如果不需要统计当前根目录本身,可在find命令的条件后增加! -path .过滤即可

内容的提问来源于stack exchange,提问作者Simos Neopoulos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 20:45:09