# 清理git历史上传的大文件

**URL:** <https://forum.beginner.center/t/topic/2503>\
**Category:** 🛠工具与编程\
**Tags:** git\
**Created:** [2025 年12 月 15 日 14:24 UTC](https://forum.beginner.center/t/topic/2503 "2025-12-15T14:24:15Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

作者： ![doggie](https://forum.beginner.center/user_avatar/forum.beginner.center/doggie/32/550_2.png) [@doggie](https://forum.beginner.center/u/doggie)\
发布日期： [2025 年12 月 15 日 14:24 UTC](https://forum.beginner.center/t/topic/2503/1 "2025-12-15T14:24:15Z")

</div>

# 先找出占空间的对象

列出历史中最大 blob（按大小排序，取前 N 条）:

```bash
git rev-list --objects --all 
git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' 
sed -n 's/^blob //p' | sort -n -k2 | tail -n 50

```

- 查看当前被跟踪的、应当忽略的路径：

```bash
git ls-files core/output

```

# 从索引中移除并提交（但是在工作目录保留）

- 先创建备份分支以防万一：

```bash
git branch backup/remove-big-files

```

- 从索引中移除（保持本地文件不变），并提交：

```sh
git rm -r --cached --ignore-unmatch core/output
git commit -m "chore: remove generated outputs and large images from index (prepare history purge)"

```

- 同时把这些路径加入 `.gitignore`，避免未来重新被跟踪。

# 从历史中彻底删除

- 推荐使用 `git filter-repo`（比 `filter-branch` 快且安全）：

```sh
# 注意：这会重写所有分支的历史，执行前请确保已备份并通知协作者
git filter-repo --force --invert-paths --path core/output 

```

- `git-filter-repo` 会在成功后提示并可能移除 `origin` 这一 remote（可根据提示重新添加）。

# 清理本地垃圾

```sh
git reflog expire --expire=now --all
git gc --prune=now --aggressive
git count-objects -vH

```

确认 `count` / `size` 大幅下降后继续下一步。

# 强推到远程（确认做好备份了再强制推送

- 因为历史被重写，需要强制推送并让所有协作者重新同步或重新克隆：

```sh
# 若 remote 被移除，先重新添加 origin
git remote add origin git@your.git.remote:repo.git # 如果需要
git push --force --all
git push --force --tags

```
