Last Updated: February 25, 2016
·
5.18K
· abishekk92

Git Reflog should be your friend

Imagine a scenario where you have rebased your branch and squashed them neatly into n commits or you have hastily done a git reset --hard.

Now all the commits have been either lost or rebased, simply put, they are no longer recognizable using their previous commit ids.

If you would like to go back to a state of the repo before you did the rebase or reset --hard, you can use git reflog.

Git internally keeps a log of state of your HEAD and all the changes that has been made to it.

git reflog

7b4ab0e HEAD@{0}: checkout: moving from 3-dummy to master
a256440 HEAD@{1}: commit (amend): Fixes Dummy Issue
d848c34 HEAD@{2}: commit: Fixes issue#3   
09dca41 HEAD@{3}: commit: Issue 3 first cut
7b4ab0e HEAD@{4}: checkout: moving from master to 3-dummy
7b4ab0e HEAD@{5}: clone: from git@github.com:abishekk92/box.git

If you've noticed, every change in state of the HEAD is logged. Once we know which state we want to move the HEAD to,


git reset --hard HEAD@{x}

If you have changes and you can't afford to do an hard reset to a particular reflog, but still want the changes from the lost commit.

git cherry-pick <commit-hash>

And also git purges its blob as soon as it reaches 5000 objects, so it wouldn't be possible to reset to a really old state of the HEAD, unless you've git configured git to do so.

1 Response
Add your response

For anyone confused on rebasing, you can "ignore that" and just think of "reflog" as a handy tool for getting back work which you think you lost.

For example, if you delete a local branch but need some of the work you had in it back, reflog still shows those commits. The commits themselves aren't deleted when you delete a branch!

The rebase example in this post above is actually saying the same thing. Rebasing can make it appear that branches are deleted (well...squashed) into a series of commits.

over 1 year ago ·