How to undo commit in Git?

Sometimes there is a need to undo some commit. Sometimes last, sometimes not. 

This article presents situations from my dev-life, when I needed to undo local and remote commits without removing local changes. It also describes a solution that I use. 

Real-life situations 

Someday I was working on my branch and I needed to switch to another one. 

git checkout undo commit

I created a commit with a temporary message because this commit was only for switching. I did not want to publish this commit. After a while I came back to my branch and I continued to work on it. I have done two commits and I pushed it to a remote repository. I finished my task, so I wanted to do merge my changes with a master branch. I noticed I did not remove temporary commit.

Another situation: I committed a file which I did not want to and pushed it to a remote. Then I realized it. 

Solution

In the first situation, a commit which needs to be edited is third. 

second undo commit

In the second, a commit is first. 

first undo commit

A solution is the same for both situations. However, the results are slightly different. 

Local repository 

To undo third commit, two previous needed to be removed as well. 

git reset –soft HEAD~3

In the second situation only one commit will be removed – the first. 

git reset –soft HEAD~1

Remote repository

In both situations, solution is the same. 

Ordinary git push won’t work. 

git push undo commit

It must be executed with force option. 

git push force undo commit

Conclusion

It is simple to undo commits. Thanks to option soft local changes will not be removed and they still will be set as ‘to be committed’. There are several other options for reset, I encourage you to check them in git documentation. In my dev-life, another option which I often use is hard, you can find it in the documentation.

0 0 vote
Article Rating
Share on
Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Maciek
Maciek
February 4, 2019 3:11 pm

This works. You can also use rebase interactive to squeeze your commit into different one (reorder etc) so you don’t need to recommit the other change (plus you can update messages etc). I think it’s also good to state that both approaches modify history, so it’s important to be extra cautious while using them just in case someone might have started to work on our changes.