Git Recovery
In this page:
Recovering a Deleted Branch
Deleting a branch with git branch -D only removes the branch pointer, not the commits it referenced, so those commits stay in the repository until garbage collection eventually removes unreachable ones. Running git reflog shows the branch's last known commit hash even after deletion, and creating a new branch pointing at that hash brings the branch fully back with its history intact.
Example: Recovering a Deleted Branch
git reflog
git branch recovered-branch a1b2c3d
Recovering After a Hard Reset
A git reset --hard moves the branch pointer and discards the commits that were on it, which feels permanent but the commits themselves usually survive in the reflog until garbage collected. Running git reflog shows an entry for the state right before the reset, and resetting again to that hash undoes the hard reset as if it never happened.
Example: Recovering After a Hard Reset
git reflog
git reset --hard a1b2c3d
Recovering an Uncommitted File
If you delete a file that was already staged or committed at some point, git checkout (or git restore in newer Git) can pull the last known version back from the index or the most recent commit. This only works for content Git already knew about — a file that was never staged or committed has no recorded version for Git to recover.
Example: Recovering an Uncommitted File
git checkout -- deleted-file.txt
git restore deleted-file.txt
Recovering After git rm
git rm removes a file from both the working directory and the staging area in one step, which is more destructive than a plain filesystem delete because it also stages the removal. If the removal hasn't been committed yet, git reset HEAD -- <file> followed by a checkout brings the file straight back; if it has been committed, you need to check out the file from the commit right before the removal.
Example: Recovering After git rm
git reset HEAD removed-file.txt
git checkout -- removed-file.txt
Recovering from a Stash
A stash is not automatically deleted after a botched apply, and even a dropped stash's commit-like object often survives in the reflog for a while, findable with git fsck --unreachable. If you know roughly what was in it, git stash list and git stash show can help you locate the exact stash entry before deciding to apply, pop, or drop it.
Example: Recovering from a Stash
git fsck --unreachable
git stash apply a1b2c3d
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: