Remove a git commit

Soldato
Joined
1 Mar 2003
Posts
5,508
Location
Cotham, Bristol
Let's say I have the following commits

F
E
D
C
B
A

And I wished to remove commit C from the stack but keep the rest as is, i.e. like so

F
E
D
B
A

Is that possible? I know of git reset, but that resets the whole stack to a point, i.e. it gets rid of anything after that commit too.
 
There is some good discussion on the option in this article.

It would help to know why you need to remove the commit to offer specific suggestions.
 
Yeah, basically what shine said :p

If you just don't want that change any more then git revert is the nice easy/clean way to do it.

There are other nastier ways, like git rebase, but you really need to be sure it's what you want to do, and if you've pushed/others have pulled then it may not even be possible (server may disable push -f)
 
A build is due to be released at the end of the week, there is a potential problem with commit 'C' so we wish to remove it and have it committed to a later build once the problem is sorted.

'C' is a cherry picked commit from a topic branch in to the main branch
 
Last edited:
git revert seems the cleanest solution, so:

git revert <commitref for C>

Which will create a new commit reversing the C commit, and then when you want to put it back you can git revert the revert commit to re-enable it (or could also cherry-pick again, same result, different commit message :p)
 
Rebase was designed for this.

Code:
git rebase -i <commit ID of a commit earlier than the one you want to keep>

It will open an editor with the commits listed - simply delete the one you don't want, then save and close the file.

Code:
git push --force
to overwrite remote repository branch.
 
imo rebase is both overkill and a 'nasty' way to achieve the goals. The only benefit of rebase over revert in this instance is that revert will have 2 commits in the history showing the code being added and then removed, whilst rebase would remove all history related to that commit.

It would also cause issues for anyone else that might have the the branch checked out next time they try to pull as their history no longer matches the servers due to the forced push.

rebase is a great tool, but I don't think it's the best tool for this situation by a long way.
 
Back
Top Bottom