Git Recovery
Git Recovery: Fixing Deleted Files and Branch Accidents
Even experienced developers delete the wrong file, commit onto a detached HEAD, or overwrite working code before staging. Knowing which recovery command matches each layer of Git keeps small mistakes from costing hours of work.
Restoring Uncommitted or Deleted Working Files
If you accidentally edited or deleted a tracked file like styles.css and have not committed yet, pull the clean version back from the staging area (or last commit) with git restore:
git restore styles.css
To restore a file from a specific past commit without changing your branch history, pass --source:
git restore --source=HEAD~2 -- index.html
Saving Commits Made While in Detached HEAD
Checking out a raw commit hash (git checkout 9fceb02) puts Git into a state where HEAD points directly to a commit instead of a named branch. If you accidentally make new commits there and switch back to main, those commits become orphaned.
Create a new branch immediately at your current commit to rescue them:
git switch -c rescue/header-fix
If you already switched away before noticing, find the orphaned commit hash in git reflog and run git branch rescue/header-fix <hash>.
Recovering Unreachable Commits with git fsck
If reflog entries expired or you dropped a stash, git fsck --lost-found scans Git's object database for dangling commits and writes their IDs so you can inspect them with git show <hash>:
git fsck --lost-found
Common Recovery Mistakes
Running git restore . discards all unstaged edits across the entire repository permanently. Always specify exact filenames (git restore styles.css) unless you are certain you want a full workspace wipe.
Frequently Asked Questions
What is the difference between git restore and git checkout -- <file>?
Both discard uncommitted working changes to <file>. git restore was introduced in Git 2.23 as a clearer, safer replacement for overloaded git checkout.
How do I recover a file I deleted and already committed?
Find the commit before the deletion with git log --diff-filter=D --summary, then restore the file from its parent commit using git restore --source=<hash>~1 -- <filepath>.
Can I recover a stash I accidentally dropped with git stash drop?
Often yes, immediately afterward. git stash drop prints the dropped commit SHA in your terminal—run git stash apply <sha> to bring it back before garbage collection runs.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With