DEV Community

Cover image for Restore lost commits - git reflog
Ismaïl BENHALLAM
Ismaïl BENHALLAM

Posted on • Updated on

Restore lost commits - git reflog

Let’s imagine you were working on your project, and you typed

git reset --hard HEAD~N
Enter fullscreen mode Exit fullscreen mode

Then you tapped Enter ↩️ by mistake, maybe..

Basically this means, that you lost the last N commits, and right now you have a clean working tree.

Don’t be afraid, there is a solution for this situation.

Introducing git reflog

The reflog is strictly local and isn’t part of the repository. It’s also not included in pushes, fetches, or clones. Git uses the git reflog tool to keep track of changes made to branch tips. It lets you go back to any commit, even if it isn’t referenced by any branch or tag

You can read more about reflogs in Gitprotect

So, how to restore a lost commit ?

To restore a lost commit, use
git reflog to see your local changes :
git reflogHere basically you can see the local logged actions by Git
Then, you can pick the SHA of the commit you want to go back to, and then run

git reset --hard e4dd6f6
Enter fullscreen mode Exit fullscreen mode

or

git cherry-pick e4dd6f6
Enter fullscreen mode Exit fullscreen mode

Don’t forget that you could use grep with git reflog to search by a commit message or a branch name… 😉

That’s cool, but does git reflog have some drawbacks ?

Reflogs or reference logs are stored only on your machine, this means you cannot push or pull them from a remote repository.

And more importantly, they get expired after a while by git-gc (git garbage collector).

The entries that have been expired are dropped, and the expiration time is taken from the configuration setting gc.reflogExpire (90 days by default)

You can read more about this here

Demonstration

Top comments (3)

Collapse
 
same7ammar profile image
same7ammar

Nice :)

Collapse
 
chaimaeelmantih profile image
chaimaeElmantih

Very helpful

Collapse
 
mouradbenamar12 profile image
Mourad Benamar

Very interesting 👍👍