DEV Community

Kumar Abhishek
Kumar Abhishek

Posted on • Originally published at abhi.page on

Recover anything in git with 'git reflog' | Notes

Direct Links:

To recover from almost anything in git, even if you have done a git reset --hard origin/main and lost all your last commits, use the following command:

git reflog
Enter fullscreen mode Exit fullscreen mode

From the official documents:

Reference logs, or “reflogs”, record when the tips of branches and other references were updated in the local repository. Reflogs are useful in various Git commands, to specify the old value of a reference. For example, HEAD@{2} means “where HEAD used to be two moves ago”… This command manages the information recorded in the reflogs.

It gives the historical info like this:

$ git reflog
c5f76d2 (HEAD -> beta) HEAD@{0}: pull origin main: Fast forward
0e373cb HEAD@{1}: commit: Updated base styles
b7aece4 HEAD@{2}: commit: Updated README
eff2f57 HEAD@{3}: commit: Added shortURL filter...
Enter fullscreen mode Exit fullscreen mode

The first 7-characters (sha-id) are the beginning of the SHA1 for that commit. You can use this to recover any lost data from that point in history.

For example, to apply our last commit back into the code base (sha-id = 0e373cb), we can merge it back with the command:

git merge 0e373cb
Enter fullscreen mode Exit fullscreen mode

We can do other stuff as well, like checkout, cherry-pick or use git show to see the diff.


Read on abhi.page

Top comments (0)