Git Reflog

It was a ordinary day. I modified codes and did commits as usual. Later I found last commit was not necessary any more. So I decided to reset it. The change was still useful so I want to keep it.

I knew related command was git reset but I was not sure which mode to use. At this circumstance I didn't go to look up the manual but use git reset --hard casually. How ridiculous I was! The result proved that. I lost all my changes.

Though I felt depressed at that moment I still believed that Git had the ability to restore the changes. So I began to search on Internet. Finally I found the answer which is git reflog.

So what is git reflog?

I prefer the explanation from Atlassian Git Tutorial:

The reflog is Git’s safety net. It records almost every change you make in your repository, regardless of whether you committed a snapshot or not. You can think of it is a chronological history of everything you’ve done in your local repo.

If I ran git reflog I would see something like this:

b0cd221 (HEAD -> master) HEAD@{0}: reset: moving to b0cd221
23b4878 HEAD@{1}: commit: Recursive function works
b0cd221 HEAD@{2}: commit: Ready to write recursive function
...

The first line is exactly my stupid behavior. The second line is the commit I lose. So I could easily restore it by running git reset --hard 23b4878. Thanks to Git I was rescued.

If you want to learn more about git reflog and its usage. I recommend two posts from Atlassian Git Tutorial: Rewriting history and git reflog. Among them The safety net: git reflog part from Rewriting history describes the same situation I face here and Recovering lost commits part from git reflog is also worth reading.