Search code examples
gitlanguage-agnosticgit-commitgit-push

Remove a file from a previous unpushed commit


I accidentally made a local commit containing an enormous (~2GB) file that I forgot to add to .gitignore. This commit also contains important changes to other files. I then made a few more unrelated local commits.

When I went to push, the push ultimately failed because of the file size and related issues, it was only then that I realized that I accidentally added that file.

Is there some way to go back and remove that file from that past commit (it's 4 commits ago and the whole series of commits remains unpushed), as if it never existed? I still want to keep the rest of the changes from the problematic commit.


Solution

  • You could do it with rebase -i, but it's a simple fix like this:

    git checkout HEAD~4
    git rm --cached the-file
    git commit --amend --no-edit
    git cherry-pick the-branch~4..the-branch # replay all revisions after the revision we modified
    git branch -f the-branch # set branch to new location
    git checkout the-branch
    

    That should do