The 2-Step Branch Recovery Protocol
- Step 1: Locate the Commit Hash with Reflog
Run
git reflogor filter by branch name:git reflog | grep "your-branch". Look for the last commit SHA right before the checkout or branch deletion occurred. - Step 2: Reattach a New Branch Reference
Once you identify the hash (e.g.,
4a89d12), executegit checkout -b your-branch 4a89d12. All files, commits, and logs will be restored immediately.
Frequently Asked Questions
Can I recover a branch after running 'git branch -D'?
Yes! 'git branch -D' only removes the branch pointer reference. The actual commits remain safely intact in your local repository database and can be located using 'git reflog'.
How long do deleted branches remain recoverable?
Git preserves unreferenced commits in the reflog for typically 30 to 90 days before running git prune or automatic garbage collection (git gc).
What is the command to restore the branch once I have the commit SHA?
Run 'git checkout -b <branch-name> <commit-sha>'. This immediately recreates the branch pointer at that exact commit.
What if I deleted a branch on GitHub / remote?
If someone else or you locally still have the commits, you can push them back. Alternatively, GitHub retains deleted branches for a short periodβyou can often restore them with one click under the 'Branches' tab on GitHub.