Squashing the wrong commit in git

I tend to do temporary commits in git pretty often. This can be for a number of reasons – either to just get a stopping point, or to push my changes on to a remote branch for some reason.

Once I’m ready to push all my changes I’ll remove all the temporary commits – the git term for this is squashing commits. To remove the temporary commit, I usually do an interactive rebase:

git rebase -i HEAD~5

Git will prompt you to select the commits you want to keep, so you would see a screen that looks something like this:

pick some-sha First commit message
pick some-sha Second commit message
pick some-sha tmp commit
pick some-sha Last commit message

Now you have to choose the commits you want, so if we want to merge the temporary commit into the second commit we have to change the pick on the third line into an s (for squash). If we want to merge the last commit into the temporary commit we have to do the same for the last line. Afterwards git will prompt you again to specify the commit message for the merge commits.

Of course, you might also squash the wrong commit. Today I squashed the temporary commit into the previous commit which meant I was merging my commit with someone else’s work. This post is the result of me figuring out how to undo this.

Undoing the commit merging

The first thing you want to do is to check the reflog.

git reflog

This will show you something like the following:

some-sha HEAD@{4}: checkout: moving from master to some-sha
some-sha HEAD@{5}: rebase -i (pick): Previous commit message (before the temporary commit)
some-sha HEAD@{6}: rebase -i (squash): Last commit message (after the temporary commit)
some-sha HEAD@{7}: rebase -i (squash): updating HEAD
some-sha HEAD@{8}: checkout: moving from master to some-sha

Now basically just pick the SHA you want move back to and then reset back to it.

git reset --hard the-SHA-you-picked

If you want to see what it looks like first you can use

git checkout -b newbranch the-SHA-you-picked

And that’s all there is to it. Git is really an amazing tool. Happy coding.