How to Recover Deleted Commit in Git Quickly and Safely
To recover a deleted commit in Git, use
git reflog to find the commit's reference, then use git checkout or git cherry-pick to restore it. This works even if the commit is no longer in the branch history.Syntax
git reflog: Shows a log of all recent HEAD changes, including deleted commits.
git checkout <commit-hash>: Switches to the commit to inspect or recover it.
git cherry-pick <commit-hash>: Applies the deleted commit onto the current branch.
bash
git reflog git checkout <commit-hash> git cherry-pick <commit-hash>
Example
This example shows how to find a deleted commit using git reflog and recover it by cherry-picking onto the current branch.
bash
git reflog
# Output shows recent commits with hashes
# Example output line: abc1234 HEAD@{2}: commit: Fix typo in README
git cherry-pick abc1234
# Applies the deleted commit back to your current branchOutput
abc1234 HEAD@{2}: commit: Fix typo in README
[main 9f8e7d6] Fix typo in README
1 file changed, 1 insertion(+), 1 deletion(-)
Common Pitfalls
- Not using
git reflogfirst to find the commit hash can lead to confusion. - Trying to recover commits after garbage collection (usually after 30 days) may fail.
- Using
git reset --hardwithout caution can delete commits permanently.
bash
git reset --hard HEAD~1 # This deletes the latest commit # Wrong recovery attempt: git checkout HEAD~1 # This moves HEAD but does not recover deleted commit # Correct recovery: git reflog # Find deleted commit hash git cherry-pick <commit-hash> # Restore the commit
Quick Reference
| Command | Purpose |
|---|---|
| git reflog | View recent HEAD changes including deleted commits |
| git checkout | Switch to a specific commit to inspect it |
| git cherry-pick | Apply a deleted commit back to current branch |
| git reset --hard | Dangerous: resets branch and deletes commits permanently |
Key Takeaways
Use git reflog to find deleted commit hashes quickly.
Recover commits by cherry-picking them onto your branch.
Avoid hard resets without backups to prevent permanent loss.
Deleted commits can be recovered if garbage collection hasn't run.
Always verify commit hashes before applying recovery commands.