How to undo a Git commit

How to undo a Git commit

What do you do when you commit something that you never intended to commit? Don't panic! Learn how to undo a commit here.

Share on facebook
Share
Share on google
Share
Share on twitter
Share
Share on linkedin
Share
undo-a-commit

I woke up this morning thinking that I should challenge myself to write the shortest technical blog in IT history.

Git makes that very easy, as it makes most things pretty straightforward – that is, of course, providing you know how it’s done…

What do you do when you commit something that you never intended to commit?

Well, you undo it:

git reset HEAD~1

What this means is that you reset the HEAD of the current branch by one commit back in history. You can even undo multiple commits in one go, all you have to do is increase the number at the end.

All the changes that the reverted commit contained are now local changes in your workspace. You can now either commit these again (e.g. to another branch or to include additional changes) or you can throw them away with git reset --hard.

If you pushed your commits before you started undoing them, there are a couple of things that you need to bear in mind:

  • You now need to push your undone commits with the --force option. However, please note that this will also undo any commits on the target branch made by other users. So take care when pushing with --force and make sure there are no other commits on the branch that follow yours.
  • Also, if you pull (rather than push) at this point, then your undone commits will be undone, i.e. you will end up back to where you started.

 

I may have failed on my target to create the shortest technical blog in history, but I hope you found this useful.


 

Want to learn more Git tricks? Clearvision offers expert Git training with courses for all abilities. Check out our training pages and let us know your requirements today!

Don’t stop your learning here! Check out Git 101, your free one stop guide to the basics of Git, including a Git cheat sheet to help you on your way!

Git-101-mockup-250x393
Share on facebook
Share
Share on google
Share
Share on twitter
Share
Share on linkedin
Share

Reader Interactions

Related blog articles

    Reader Interactions