如何删除git中错误提交的大文件

时间:2011-11-10 16:55:43

标签: git git-rewrite-history

  

可能重复:
  How to purge a huge file from commits history in Git?

我做了一件蠢事。想象一下,我提交了一个100MB的文件。然后我看到这个并删除此文件并再次提交。这是删除文件的正常过程。

但现在副作用是我的历史很重,因为它保存了这个大文件(我相信这就是为什么它很重)。我只使用本地git,所以我不在任何服务器中同步。

如何最终删除此文件并节省磁盘空间?

3 个答案:

答案 0 :(得分:140)

您可以使用git filter-branch命令执行此操作,如下所示:

git filter-branch --tree-filter 'rm -rf path/to/your/file' HEAD

您可以在此处找到更多文档http://dalibornasevic.com/posts/2-permanently-remove-files-and-folders-from-a-git-repository

答案 1 :(得分:26)

您要查找的命令是filter-branch。它允许您从登记中永久删除文件。这篇博客有一个很棒的教程,介绍如何从存储库中删除有问题的文件

答案 2 :(得分:16)

您可以从David Underhill获取此优秀脚本,以从git存储库中删除该文件:

#!/bin/bash
set -o errexit

# Author: David Underhill
# Script to permanently delete files/folders from your git repository.  To use 
# it, cd to your repository's root and then run the script with a list of paths
# you want to delete, e.g., git-delete-history path1 path2

if [ $# -eq 0 ]; then
    exit 0
fi

# make sure we're at the root of git repo
if [ ! -d .git ]; then
    echo "Error: must run this script from the root of a git repository"
    exit 1
fi

# remove all paths passed as arguments from the history of the repo
files=$@
git filter-branch --index-filter "git rm -rf --cached --ignore-unmatch $files" HEAD

# remove the temporary history git-filter-branch otherwise leaves behind for a long time
rm -rf .git/refs/original/ && git reflog expire --all &&  git gc --aggressive --prune