What is git reflog, and how does it help you recover lost commits?
The reflog is a local log of every position HEAD and your branches have been at. If you reset or delete something by mistake, you find the old commit hash in the reflog and point a branch back to it.
Explain it simply
git log shows the history of the project. The reflog shows the history of what you did: every checkout, commit, reset and rebase. It is like your browser history, which can bring back a page after you closed it by mistake.
After a bad git reset --hard, the commits are no longer on the branch but still exist in the repository for a while, and the reflog keeps entries for at least 30 days by default. git reflog lists them with names like HEAD@{2}. Create a branch at the right one, or reset to it. Reflogs are local only; they are never pushed.
Example
git reset --hard HEAD~3 # oops
git reflog
# 8a1b2c3 HEAD@{0}: reset: moving to HEAD~3
# f4d5e6a HEAD@{1}: commit: Add checkout page
git reset --hard f4d5e6a # or: git branch rescue f4d5e6aWhat to say in the interview
"The reflog records where HEAD and branch tips have been, locally. After a mistaken reset, rebase or deleted branch I run git reflog, find the earlier hash, and recover with git reset or git branch. It is local, and entries eventually expire."
Common mistakes
- Expecting the reflog to recover uncommitted changes; it only tracks commits.