debuggitMajor
Recovering lost commits with git reflog
Viewed 0 times
reflogrecover commitslost commitsundo resetdeleted branch recovery
Error Messages
Problem
After a
git reset --hard, git rebase, or accidental branch deletion, commits appear to be permanently lost.Solution
Git's reflog records every movement of HEAD for 90 days (by default). Use it to find and restore lost commits:
git reflog
# Shows: a1b2c3d HEAD@{2}: reset: moving to HEAD~3
# Restore the lost state
git reset --hard HEAD@{2}
# Or create a new branch at the lost point
git branch recovered-work HEAD@{2}
For a deleted branch:
git reflog | grep 'branch-name'
git checkout -b branch-name <found-sha>
git reflog
# Shows: a1b2c3d HEAD@{2}: reset: moving to HEAD~3
# Restore the lost state
git reset --hard HEAD@{2}
# Or create a new branch at the lost point
git branch recovered-work HEAD@{2}
For a deleted branch:
git reflog | grep 'branch-name'
git checkout -b branch-name <found-sha>
Why
The reflog is a local log of all HEAD changes, including those that make commits unreachable from any branch. It is not shared with remotes — it is purely local to your machine.
Gotchas
- Reflog entries expire after gc.reflogExpire (default 90 days) — don't wait too long
- Reflog is per-worktree — check the correct worktree's reflog if using git worktree
- Cloning a repo does not copy the original repo's reflog
Code Snippets
Using reflog to recover lost commits and branches
# See all recent HEAD movements
git reflog
# Find a specific point
git reflog | grep 'before rebase'
# Restore to that point
git reset --hard HEAD@{3}
# Non-destructive: create a branch at the lost point
git branch rescue HEAD@{3}
# Recover a deleted branch
git reflog --all | grep 'deleted-branch'
git checkout -b deleted-branch a1b2c3dContext
After accidental hard reset, rebase gone wrong, or branch deletion
Revisions (0)
No revisions yet.