Working with Git and Visual Studio – Restore a deleted branch in Git

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:

View commit history and branch status
View commit history and branch status

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:

Make few commits in another branch

Now, let’s checkout master branch and delete the branch quickFix:

Switch back to master branch and delete branch quickFix
Switch back to master branch and delete 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:

Checking git reflog

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:

checkout the commit made
checkout the commit made at tip of deleted branch

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 <new-branch-name>’ to create a new branch from same commit:

create a new branch pointing to the 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.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s