Git Reflog

The reflog is Git’s safety net. It is a private diary which records every time the tip of your branches or HEAD moves: commits, resets, merges, switches and more. When you think you lost a commit, the reflog usually still has it.

Syntax

git reflog
git reflog show <branch>
git reset --hard HEAD@{1}

Recover from a wrong hard reset

We make a mistake: we reset hard two commits back.

Terminal output

$ git reset –hard HEAD~2
HEAD is now at 1c2b832 Add note one
$ git log –oneline
1c2b832 (HEAD -> main) Add note one

The commits “two” and “three” are gone from the log. But look at the reflog:

Terminal output

$ git reflog
1c2b832 (HEAD -> main) HEAD@{0}: reset: moving to HEAD~2
8e4e3e1 HEAD@{1}: commit: Add note three
2bee720 HEAD@{2}: commit: Add note two
1c2b832 (HEAD -> main) HEAD@{3}: commit (initial): Add note one

Each line has a name like HEAD@{1}, which means “where HEAD was one move ago”. The commit we need is at HEAD@{1}. We go back to it:

Terminal output

$ git reset –hard HEAD@{1}
HEAD is now at 8e4e3e1 Add note three
$ git log –oneline
8e4e3e1 (HEAD -> main) Add note three
2bee720 Add note two
1c2b832 Add note one
$ cat notes.txt
one
two
three

Recover a deleted branch

Terminal output

$ git switch -c feature-x
Switched to a new branch 'feature-x'
$ echo "feature work" > feature.txt
$ git add .
$ git commit -q -m "Add feature work"
$ git switch main
Switched to branch 'main'
$ git branch -D feature-x
Deleted branch feature-x (was 6349b69).
$ git reflog -4
8e4e3e1 (HEAD -> main) HEAD@{0}: checkout: moving from feature-x to main
6349b69 HEAD@{1}: commit: Add feature work
8e4e3e1 (HEAD -> main) HEAD@{2}: checkout: moving from main to feature-x
8e4e3e1 (HEAD -> main) HEAD@{3}: reset: moving to HEAD@{1}

The branch is deleted, but its last commit is in the reflog, one step back from the switch. We create a branch there again:

Terminal output

$ git branch feature-x-restored HEAD@{1}
$ git log –oneline feature-x-restored
6349b69 (feature-x-restored) Add feature work
8e4e3e1 (HEAD -> main) Add note three
2bee720 Add note two
1c2b832 Add note one

How long does the reflog keep data?

By default entries stay for 90 days, and for 30 days if the commit is not reachable from any branch. After that, Git can clean them with garbage collection. So act soon.

Important points

  • The reflog is local. It is not pushed, and a fresh clone has an empty reflog.
  • It only helps for committed work. Changes that you never committed cannot be recovered with it.
  • git reflog shows HEAD. For one branch use git reflog show main.
Note: When you feel that you destroyed something with reset, rebase or amend, stop and run git reflog before doing anything else. Next: Git SSH Key.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.