How to use git reflog to recover lost commits
· Category: Git
Short answer
git reflog records every HEAD movement, allowing you to recover commits even after destructive operations.
Steps
- View the reflog:
git reflog
- Find the commit hash before the destructive operation.
- Checkout or reset to that commit:
git checkout abc1234
git branch recovered-branch
- Or reset a branch:
git reset --hard abc1234
Tips
- Reflog is local and expires after a configurable time (default 90 days).
git reflog show mainshows reflog for a specific branch.- Reflog is your safety net; learn it before you need it.
Common issues
- Reflog only works locally; commits never pushed cannot be recovered on a new machine.
- Garbage collection may remove unreachable objects after the expiry period.