Recovering deleted GIT branch

Today I'm back at work, so as a regular routine, I'm cleaned my list of “stale” git branches both locally and remotely. And I have a nice handy shell script to do that. So with a single command I can completely get rid of a branch :-). This is awesome most of the time… But it's not that handy when you make a mistake, and you delete a branch you actually needed!

Was I really frightened when I realized that I had just deleted a branch containing some work that was not merged yet on our master branch… If there is something I really hate, it is to delete information, or, in other words, having to rethink about some work I've already done before (In fact, I'm ready to toss that this is a general developer trait ;-) )

So, I started to look for a way to fix that hoping that git would be smart enough to be able to handle such stupid mistakes, and indeed it is! I found a few links with indications on how to proceed, such as:

And this is worth mentioning here, just in case this could help someone else:

Let's assume you just deleted your branch “my_feature_branch”, and you can't access it locally or remotely anymore, with something like:

git push --delete origin "my_feature_branch"
git branch -D "my_feature_branch"

Then you cry… because you just lost hours of work… But fear not my child, you can still be saved! :-)

⇒ The first think you need to do is to retrieve the sha of the last commit you did on that branch you just removed. To do this, we use the git reflog command. For instance in my case, I had removed a branch called issue665_rcs_random_commands, and I got the results:

$ git reflog
a64869a HEAD@{0}: pull: Fast-forward
8346ad0 HEAD@{1}: pull: Fast-forward
7ab3da1 HEAD@{2}: checkout: moving from issue665_rcs_random_commands to master
703f3fe HEAD@{3}: commit: Issue #665: Fixing AVT callbacks execution in main thread.
f52d0d1 HEAD@{4}: commit: Issue #665: preventing AVT leave acquisition lock without valid input stream.
a650707 HEAD@{5}: commit: Issue #665: Fixing unit tests.

From that output, I could see that the last commit I did on that branch for my “issue #665” had an sha value of 703f3fe.

⇒ Then you can restore the branch with the following command:

git branch my_feature_branch 703f3fe

You are (most probably?) free to change the branch name when doing this operation.

And then, bingo! You should have your branch name back into your local branch list. And you can get back on it with the usual command:

git checkout my_feature_branch

That's it! Those few commands saved my day already. They might save yours too.

  • blog/2019/0102_recovering_deleted_git_branch.txt
  • Last modified: 2020/07/10 12:11
  • (external edit)