【问题标题】:How do I remove a big file wrongly committed in git [duplicate]如何删除在 git 中错误提交的大文件 [重复]
【发布时间】:2011-12-26 08:45:46
【问题描述】:

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

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

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

我怎样才能彻底删除这个文件并节省磁盘空间?

【问题讨论】:

标签: git git-rewrite-history


【解决方案1】:

您可以使用 git filter-branch 命令来完成,如下所示:

git filter-branch --index-filter "git rm -rf --cached --ignore-unmatch path_to_file" HEAD

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

【讨论】:

  • 请注意,它还会删除当前签出的版本,因此如果需要保留它,请确保您有备份。
  • 我使用的是 Windows。我不得不将单引号换成双引号。
  • @rleelr 我认为 github 页面提供了一个干净的解决方案而不影响其他文件:help.github.com/articles/…
  • 我有这个错误:Cannot rewrite branches: You have unstaged changes.
  • 1. git filter-branch --tree-filter 'rm -rf path/to/your/file' HEAD 2. 如果出现此错误:无法重写分支:您有未暂存的更改。 3.git stash save 4.git push origin master --force
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    您可以从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
    

    【讨论】:

    • 要小心,因为如果你像我这样有很多提交,这个脚本可能会运行很长时间(~30k,它会持续一整天)。
    • @AlainP 你应该摆脱旧的提交,谁需要那么多(30K)? :)
    猜你喜欢
    • 2017-09-18
    • 2011-01-29
    • 2012-10-09
    • 2018-08-11
    • 2013-08-11
    • 2020-06-19
    • 2012-10-10
    • 2014-09-07
    • 2011-11-01
    相关资源
    最近更新 更多