0 Comments

One of the most daunting things for developers new to Git is understanding how they can undo commit mistakes. And the git reset command is a powerful tool to help with that. But it can seem confusing. What does the magical git reset --hard HEAD~1 invocation that you may have seen on stack overflow actually do? And what is the difference between a “hard” and a soft reset?

In this video, I demonstrate three situations in which the git reset command can help:

The video demonstrates in more detail, but the three scenarios I discuss are:

1. Throwing away a junk commit. If you’ve just committed to your local repository and now you decide that you want to throw that away, you can use git reset --hard HEAD~1 to jump the current branch back to the previous commit (that’s what HEAD~1 means – go back one commit from the current position), and reset the working directly back to the state it was in at the time of that commit (that’s what the --hard flag means)

2. Committing too early.If you’ve just committed but realize that you should have changed just one or two things first, the git reset command can be used without the --hard flag to put the current branch back where it was, you can simply use git reset HEAD~1  and your working directory won’t change at all. That way you can make a few final tweaks before re-performing the commit.

3. Committing on the wrong branch.Sometimes you make a commit and then realise that you’d intended to create a new branch for that commit, rather than working directly on the master branch. Getting out of this situation is nice and easy. First, keep your new commit safe by creating a new branch that points at it. For example git branch feature1.  And now, we’re still on the master branch, so we can point that back to the previous commit with git reset --hard HEAD~1. And then you can checkout your new feature branch and continue working on that.

Note:There is one important caveat with these git reset tips – if you’ve already pushed to the server, things can get tricky. Others may have pulled and built on top of commits you want to throw away. In these situations it’s usually better to use git revert to create a new commit that undoes the mistake. That’s generally a lot safer.

By the way the tools I use in the video are posh git and GitViz.

Vote on HN
comments powered by Disqus