Skip to content

Instantly share code, notes, and snippets.

@zgulde
Last active September 11, 2016 04:58
Show Gist options
  • Select an option

  • Save zgulde/20e42b84a3e4b07b64374c7f17ab1737 to your computer and use it in GitHub Desktop.

Select an option

Save zgulde/20e42b84a3e4b07b64374c7f17ab1737 to your computer and use it in GitHub Desktop.

Remove a file from git history

Note: you will need a clean working directory to do this.

We will be rewriting history! This will entirely remove the commit from history

You should probably only do this if you really need to remove a file entirely from history. For example if the file you added is too large and GitHub won't accept it. If you are just trying to undo what a commit has done, there are better ways to do it without modifying history, check out git revert.

We are assuming that the problematic file was added in one commit and not modified since.

Explicit steps and explanation

  1. find the sha of the commit that introduced the bad file

    # will display the hash of the commit where the file was introduced
    git log --pretty='%H' problematic-file.jpg | tail -n 1

    replace problematic-file.jpg with the file that you want to remove from history.

    copy down that hash

  2. get rid of that commit

    git rebase --onto <hash>^ <hash> HEAD

    Replacing <hash> with the commit you coppied in the previous step

    Note that we will paste the hash twice, the first time with a ^ after it

  3. create a new branch based off of where we are and switch to it

    The previous command will leave us in a detached HEAD state, so we'll need to create a branch based off of our current state.

    git branch branch-without-problematic-file
    git checkout branch-without-problematic-file
  4. do a git log to verify that the problematic file is not longer in your commit history

    git log
    
  5. delete the old master branch as it still contains the problematic file

    Note: replace master with the branch you are working from if it's different than master

    at this point we should be in our branch-without-problematic-file branch

    git branch -D master
    
  6. rename our branch to master

    git branch -m master
    

Now we will have removed the problem file from our commit history!

Shortcut

# from 'my-branch' remove 'problem.file' from 'my-branch's history entirely
for commit in $(git log --pretty='%H' problem.file); do git rebase --onto $commit^ $commit my-branch; done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment