Search code examples
gitgit-commit

How to remove a commit from the middle of a branch


I've made some commits and have pushed it to my remote repo. One of those I want to remove. It includes only one binary file, which was changed only in that commit in that branch. How to remove it without harm for later commits?


Solution

  • You can use interactive (-i) rebase to remove a previous commit.

    $ git log                          # copy the target commit 
    
    $ git rebase -i <target-commit>~1  # start rebase from the previous commit of target commit
    

    An editor will open with a list of commits, one per line. Each of these lines begins with pick. Comment out your target commit's line (Put # at the start of target commit line).

    OR, put drop or d instead of commenting out the line with #.

    $ git rebase --continue      # repeat the command until finish rebase
    

    Now, you need to do force (-f) push to remote since git history has been changed!

    $ git push -f origin HEAD