git reflog — Recovering Lost Work
The reflog (reference log) records every time a branch tip moves. Even when commits seem "lost" after a reset or rebase, the reflog remembers where you were.
How It Works
Every time HEAD changes — commit, checkout, reset, merge, rebase — Git writes an entry to the reflog:
HEAD@{0}: commit: Add login feature
HEAD@{1}: checkout: moving from main to feature
HEAD@{2}: commit: Fix typo in README
HEAD@{3}: reset: moving to HEAD~2
Basic Commands
git reflog # show reflog for HEAD
git reflog show main # show reflog for a specific branch
git reflog --relative-date # show timestamps instead of indices
The Safety Net
The reflog is your undo button for almost anything in Git. Accidentally deleted a branch? Reset too far back? The commits are still there — the reflog knows where.
Before reset: A — B — C — D (HEAD)
After reset: A — B (HEAD) C — D (still exist!)
The commits C and D aren't gone. They're just unreachable from any branch. The reflog still points to them.
Recovering a Lost Commit
git reflog # find the commit hash
git checkout <hash> # inspect it
git branch recovered <hash> # create a branch to save it
Or use git reset:
git reset --hard HEAD@{2} # move HEAD back to reflog entry 2
Try it!
Practice losing and recovering commits:
- Set up a repo with several commits:
git init && echo "first" > file.txt && git add file.txt && git commit -m "First commit" - Add a second commit:
echo "second" >> file.txt && git add file.txt && git commit -m "Second commit" - Add a third commit:
echo "third" >> file.txt && git add file.txt && git commit -m "Third commit" - Check the log:
git log --oneline— you should see three commits - Reset back to the first commit:
git reset --hard HEAD~2 - Check the log again:
git log --oneline— only one commit remains - Use the reflog to find the lost commits:
git reflog - Recover the third commit:
git reset --hard HEAD@{1} - Verify recovery:
git log --oneline— all three commits are back
Reflog Expiry
Reflog entries don't last forever. By default:
- Reachable entries expire after 90 days
- Unreachable entries expire after 30 days
This means you have at least 30 days to recover lost commits. After that, git gc may clean them up.
When Reflog Saves You
- Accidental
git reset --hard - Deleted a branch with unmerged work
- Bad rebase that lost commits
- Need to find "what did I do yesterday?"