Recover a reset or deleted commit in Git with git reflog


In previous post, we know how to reset (delete) a commit that’s pushed to the remote repository server using git reset --hard and git push origin -f.

This post show you how to recover a reset or deleted commit with git reflog. We can find the commit that we want to be on in that list and we can reset to it.

Reflogs are stored in directories under the local repository’s .git directory. git reflog directories can be found at .git/logs/refs/heads/., .git/logs/HEAD, and also .git/logs/refs/stash if the git stash has been used on the repo.

Case study

There is an example for this case. Assume that the commit named "add deployed on IIS" is the deleted commit with git reset --hard and git push origin -f. We want to recover this commit and bring back to the local repository.

Step 1: Using git reflog to show all the lastest commit. There is a line:

1027e32 HEAD@{2}: commit: add deployed on IIS

Step 2: Using git branch to create a new branch based on the old state commit 1027e32

git branch a 1027e32

Step 3: Checkout the branch a. This will get us back to the desired commit.

git checkout a

That’s all for recovering the reset/deleted commit on the remote repository.

Summary

In this tutorial we discussed the git reflog command. Some key points covered were:

  • view reflog for commit
  • undo a git reset — hard using the reflog


Personal experiment
Nam Le.


Leave a Reply