Today we are going to see how to recover a commit that was accidentally amended.
Let’s say we are in the following situation:
$ git log --oneline eb92db3c Second commit 2fddb4b3 First commit
We make some changes, stage them, and accidentally run git commit amend:
$ git commit --amend [master c982fb5] Second commit (amended) Date: Wed Dec 9 22:06:43 2015 +0100 1 file changed, 1 insertion(+) create mode 100644 second.txt
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`:
git branch -f master eb92db3
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:
git checkout --detach HEAD git branch -f master eb92db3 git checkout master
The second problem requires the use of the reflog, i.e. a registry that tracks all the movements of our branches. We can run:
$ git reflog master c982fb5 master@{0}: commit (amend): Second commit (amended) eb92db3 master@{1}: commit: Second commit 2fddb4b master@{2}: commit (initial): First commit
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.