Photo of Christoph Rumpel

Recover a deleted branch in Git

Have you ever forgotten to merge a branch and deleted it? Yep, I did it. But don't panic, fortunately there is an easy way to recover that data.

The scenario

I am working with Git in all of my projects. If you haven't used it, stop reading and start using it now. No really, leave my site and get yourself familiar with the best version control ever here.

In bigger project I am using a a [feature branch workflow](https://de.atlassian .com/git/tutorials/comparing-workflows/feature-branch-workflow/). Every new code, in my case always a bugfix or a feature, gets inside a new branch. When I am finished, I need to merge it to main branch. (develop, staging, master, production etc.) This is what I forgot to do.

After merging it to my main branch, I normally delete the branch to prevent a mess in my repositories. This is what I didn't forgot. Damn!

Note: Use the -d flag instead of the -D flag when you delete a branch. This way you get noticed if the branch wasn't merged yet.

Checkout to rescue

So what can we do about it? First we need to get the hash / id from our last commit of the deleted branch. Every commit gets a 40 digit hash code which represents the whole commit. Additionally there is a short one. We can use both of them.

If you just deleted the branch, the commit's id is right in front of you. (e2d052)

$ git branch -D feature/addCoolStuff 
Deleted branch feature/addCoolStuff (was e2d052e).

If you don't see the id in your current console, you need to look for it. Use the git reflog command to show almost every change that has been done to your repository. It also shows commit messages, which comes in useful.c

$ git reflog
a06bbba HEAD@{0}: checkout: moving from restoredCommit to master
e2d052e HEAD@{1}: checkout: moving from master to restoredCommit
a06bbba HEAD@{2}: checkout: moving from feature/addCoolStuff to master
e2d052e HEAD@{3}: commit: Add super cool comment
a06bbba HEAD@{4}: checkout: moving from master to feature/addCoolStuff
a06bbba HEAD@{5}: commit (initial): Initial commit

And again we just take the right id e2d052e. The last thing we need to do, is to restore that commit. We are going to tell git to create a new branch with that data.

git checkout -b newBranchName e2d052e

And voila, we're back on track.


Git is a beast! It is great, complicated, awesome, annoying, lovely, bitchy and beautiful. Luckily you can undo almost everything in Git and today I covered how to recover a deleted branch.

Let's stay in touch

Sign up for my newsletter and I will let you know about more content and new projects of mine once a month.