Git Recovery
Git recovery means bringing back lost commits, branches, or files.
Even after a reset or delete, Git’s internal history makes it possible to undo mistakes.
When to Use Git Recovery
Use recovery tools when you:
- Accidentally delete a branch or file
- Reset to an older commit and lose recent changes
- Need to restore lost commits or edits
Recover Lost Commits with git reflog
Git keeps a log of where HEAD and branches have pointed recently.
Show the reflog:
git reflog
Example output:
e56ba1f (HEAD -> master) HEAD@{0}: commit: Revert "Just a regular update"
52418f7 HEAD@{1}: commit: Just a regular update
9a9add8 (origin/master) HEAD@{2}: commit: Added .gitignore
81912ba HEAD@{3}: commit: Corrected spelling error
Find the commit hash you want to bring back.
Restore a Deleted Branch
If you deleted a branch, but its commits still appear in the reflog, recreate it:
git checkout -b branch-name <commit-hash>
Example:
git checkout -b feature-branch 52418f7
You’ll have the branch back at that commit.
Recover a Deleted or Changed File
If you removed or changed a file and want the last committed version back:
git restore filename.txt
This restores the file from the latest commit on your current branch.
Recover After git reset --hard
Even after a hard reset, the reflog remembers previous commits.
Step 1: Find the old commit:
git reflog
Example output:
e56ba1f (HEAD -> master) HEAD@{0}: reset: moving to HEAD@{2}
52418f7 HEAD@{1}: commit: Just a regular update
9a9add8 HEAD@{2}: commit: Added .gitignore
Step 2: Move HEAD back:
git reset --hard HEAD@{2}
Your branch will be restored to that commit’s state.
Best Practices
- Commit your work regularly to minimize loss.
- Use git reflog to track lost commits.
- Use git restore to recover accidentally deleted or modified files.