GIT undo a commit that isn't the most recent, rebase all commits since

118,601

Solution 1

git rebase -i is the right command, but you want to do it from the branch with the latest changes, and pass in the revision that is the "base" of the rebase operation (the revision immediately before the bad commit). So, if you have created a branch last-good-commit that points to the last good commit, you would want to run the following while on master:

git rebase -i last-good-commit

Solution 2

The easiest way to do what you want is to stay on (or re-checkout) the branch that you want to edit and run something like this.

git rebase --onto <sha1-of-bad-commit>^ <sha1-of-bad-commit>

This will rebase everything since the bad commit onto the bad commit's parent, effectively removing the bad commiit from your current branch's history. Of course you will need to resolve any conflicts if they occur.

Solution 3

Using rebase, I was not able to push the changes to the remote, and my rebase was canceled at each pull.

I succeeded in reverting a precise commit (not the last one) with, simply:

git revert <sha-of-bad-commit>

And then I was also able to push on the remote

Share:
118,601
rjmunro
Author by

rjmunro

Twitter: http://www.twitter.com/rjmunro

Updated on December 18, 2020

Comments

  • rjmunro
    rjmunro over 3 years

    Earlier on, I committed some code which at the time seemed like a good idea, but in fact it made things worse. I'd like to remove the change from the history as it is not helpful, and rebase all commits since - they should all merge without issues.

    I tried creating a new branch (called newMaster) immediately before the bad commit (with gitx), checking it out and running:

    git rebase -i master
    

    Which AFAICS should have given me a list of the commits on master and the option to merge or not merge them, but instead it said noop, and fast forwarded newMaster to be equal to master.

    What is the easiest way to do what I need?