A few tips on git reset

I’ve learned a couple of handy tricks with git reset during the last few weeks (mostly by following Github employees on Twitter!).

This first tip is really handy when you have messed up your master branch by forgetting to create a new branch or when you want to redo your commits. For example, if you want to submit a beautiful, handcrafted pull request but your recent commit history looks really nasty then run this command:

git reset --soft origin/master

This will rollback your branch to the same commit as origin/master but it keeps all the changes you have done. So the commits are removed but all the files you have changed are moved to staging. You can then unstage and stage files and handcraft logical commits with fantastic commit messages. Don’t forget to do a git fetch origin/master first and a git rebase afterwards!

The 3 modes

There are three modes for git reset: soft, mixed and hard. See this post on ProGit for an in-depth explanation. If I had used –mixed instead of –soft then I would also have unstaged all my changes. While –hard would have thrown away all my changes and my local repo would look exactly like origin/master. So be careful with hard resets as the only way you might be able to get your changes back is using something like git reflog.

The Last Trick

git reset will take any git reference (SHA) or treeish.  Examples of treeishes are:

  • origin/master – which is a remote branch name
  • HEAD~ – the previous commit of wherever HEAD is pointing
  • master~2, master^^ – two commits back from the current master HEAD
  • master@{5} – 5 commits back from current master HEAD
  • 981c1cc775845200e6cb5ad6e9d8d10f2d3e1cf8 – a complete SHA
  • 981c1cc775845200e – a partial SHA

To quickly reset your branch HEAD to a previous commit, choose an appropriate treeish for a previous commit and pass it into git reset. Here is an example using a complete SHA which I found by using git log to see my recent commits:

git reset --hard eff383a443e8bfe1859063079bd15f712509e2c5