Restore lost commits in Git


cs CZE

So, you’ve called a git reset --hard on a wrong branch or did some other destructive action (perhaps a wrong rebase, amend etc.), and lost some important commit(s) in the repository.

Well, fortunately nothing is actually lost 1), and Git allows us to recover such detached commits 2). Even amended commits can be restored back to the previous state using the following technique.

First, we need to find out the lost commit reference in the Git revision log. That can be done by the git reflog command:

$ git reflog
30e8092 HEAD@{0}: reset: moving to 30e80927af84d5547f1769b8686a4d2119a305f0
3fa5267 HEAD@{1}: commit: Introduced a new important method
266af36 HEAD@{2}: commit (amend): Fix the issue
c7ead11 HEAD@{3}: commit: Fix the issue
30e8092 HEAD@{4}: commit: Release 1.0

For bigger repositories with longer revision logs, one might want to use the grep command to only see the appropriate commits, if we remember at least a part of the commit message. For example:

$ git reflog | grep "Introduced"
3fa5267 HEAD@{1}: commit: Introduced a new important method

So, the “bad reset” moved the current branch to 30e8092 (“disconnecting” the commits 3fa5267, 266af36 and c7ead11), and we’d like to set the branch back to 3fa5267. That is actually rather easy to do, by checking out the correct branch and resetting it to the correct commit:

$ git checkout my-branch-name
$ git reset --hard 3fa5267

Et voilà, the world is saved!
(the checkout command is not necessary, if the actual branch is already the correct one – but check twice, to not reset some other wrong branch again)

Alternatively, we might want to create a new branch for that commit:

$ git branch lost-commit 3fa5267
$ git checkout lost-commit

1) As long as we do not call git gc to garbage-collect the dangling records.

2) Note that the uncommitted changes in the working directory, which were accidentally overwritten by e.g. a checkout or reset, cannot be restored (at least not by git – the files might still be open in the editor, disk recovery tools might be able to recover them, etc.).


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s