Sometimes, you delete the branch that you were working on thinking that it was not needed later, only to realize that you need it again. If you are familiar with the git bash shell or native git commands, there is nothing much to worry.
It’s possible to restore deleted branch in Git if you happen to remember few basic details. In this quick blog post, we are going to cover on how to restore a deleted branch in Git.
For demo purposes, we’ll start with one of the existing repos that we are using:

As you can see, we have few commits and our HEAD is pointing to master branch. Let’s create a new branch named quickFix and make couple of commits:
Now, let’s checkout master branch and delete the branch quickFix:

Now, to restore the new branch, you need to know the last commit that was pointing to the tip of the deleted branch. In our case, this is easier as we know the HEAD was pointing to commit 5bec225. However, if you forget that for some reason, you can also check the git reflog and try to find the last checkout made before deleting the branch:
From reflog, we can make a guess that since we switched from quickfix branch to master branch, last used commit was 5bec225. So that most likely be the HEAD of the now deleted quickFix branch.
Once we have above info, we can run below command to first checkout the commit made:

You’ll see warning message that HEAD is in detached state. This makes sense as branch is not restored yet. We can now run the command ‘git checkout -b ‘ to create a new branch from same commit:
Off course, strictly speaking, we have not restored deleted branch. However, since branch is just a pointer to the commit, we merely create a new branch (with same name or different name) pointing to the same commit as deleted branch. So end results are same.
Remember that a branch is not a snapshot, but a pointer to one. So when you delete a branch you delete a pointer.
You won’t even lose work if you delete a branch which cannot be reached by another one. That’s why Git is unable to delete a branch which cannot be reached by using -d. Instead you have to use git branch -D.
[…] This post is part of the series of posts on the Git and Visual Studio where we are discussing in detail on meaning of basic git operations, how to do them in Git and Visual Studio both and understand the difference of both tools. You can find the previous blog post here. […]
LikeLike