Restore deleted Git branch
April 15, 2015 • ☕️ 1 min read
It can happen to anyone: remove branches that has not been merged.
Quick fix:
git reflog
- Look for last commit in deleted branch, copy it SHA (first column).
git checkout [sha]
git checkout -b restored-branch
- You are amazing!
Details?
A branch in Git is simply a lightweight movable pointer to commit.
HEAD is pointer to commit you currently have in working copy.
When you delete branch (with git branch -D feature-branch
) git just delete this pointer
Fortunately we can create new branch on this commit.
First you need to find SHA of this commit with git reflog
7a94c18 HEAD@{0}: commit: last commit
3fe702c HEAD@{1}: checkout: moving from feature-branch to master
8879406 HEAD@{2}: commit: feature commit
3fe702c HEAD@{3}: checkout: moving from master to feature-branch
3fe702c HEAD@{4}: commit: second comit
e57b217 HEAD@{5}: commit (initial): Initital commit
Now, move HEAD pointer to feature commit. git checkout 8879406
And finally create new branch
git checkout -b restored-branch
ps. always check git response to command: it notifies when you try to do something stupid.