Git: Getting back an amended commit

Today we are going to see how to recover a commit that was accidentally amended.

Let’s say we are in the following situation:

We make some changes, stage them, and accidentally run git commit amend:

The history is rewritten, so how to bring back the lost commit? If we had the git log output in our terminal that would be easy, we could just force some branch, say master, to point to the commit, in our case eb92db3c:

This would work but has two main problems:

– It doesn’t work on the current branch
– We must know the good commit’s SHA1.

The first problem can be addressed detaching HEAD temporarily:

The second problem requires the use of the reflog, i.e. a registry that tracks all the movements of our branches. We can run:

Here we can see that the last movement was a commit amend, so we just need to take the SHA1 of the previous commit and carry out the procedure above.

Categories: git