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.
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
--forceoption. However, please note that this will also undo any commits on the target branch made by other users. So take care when pushing with
--forceand 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.
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!