Guide

How to recover a deleted git branch

A branch is just a name pointing at a commit. Deleting it removes the name; the commits stay in your repository until git’s garbage collection cleans them up.

1. Use the SHA git printed when you deleted it

If the terminal is still open, the delete command told you where the branch was:

$ git branch -D feature
Deleted branch feature (was 4c5d6e7).

Recreate it at that commit:

git branch feature 4c5d6e7

2. Otherwise, search the reflog

The branch’s own reflog is deleted with the branch, but HEAD’s reflog remembers every commit you had checked out. Search it for the branch name:

git reflog | grep feature

7a8b9c0 HEAD@{4}: checkout: moving from feature to main
4c5d6e7 HEAD@{5}: commit: Finish settings page

The line moving from feature to main means the commit just below it, 4c5d6e7, was the last one you had on feature. Check it, then recreate the branch:

git log --oneline -5 4c5d6e7
git branch feature 4c5d6e7

If you committed to the branch after that, look for later commit: entries made while you were on it.

3. If you never checked it out: git fsck

A branch you fetched but never checked out won’t be in HEAD’s reflog. If it was pushed, the easiest fix is to fetch it again: git switch feature recreates it from origin/feature. If it only ever existed locally, list commits that nothing points to any more:

git fsck --no-reflogs --unreachable | grep commit
git show --stat <sha>     # inspect each candidate

When you find the tip, run git branch feature <sha>.

Deleted on the remote too?

Once the branch is back locally, push it again: git push -u origin feature. If someone else still has a copy, they can push it for you.

Don’t wait. With default settings, reflog entries for commits no branch points to expire after 30 days, and git gc can then delete those commits. git gc --prune=now deletes unreachable commits that no reflog entry protects straight away.