Git undo local branch delete

Stefan Kendall picture Stefan Kendall · Oct 26, 2010 · Viewed 98.4k times · Source

I just deleted the wrong branch with some experimental changes I need with git branch -D branchName.

How do I recover the branch?

Answer

bobDevil picture bobDevil · Oct 26, 2010

You can use git reflog to find the SHA1 of the last commit of the branch. From that point, you can recreate a branch using

git branch branchName <sha1>

Edit: As @seagullJS says, the branch -D command tells you the sha1, so if you haven't closed the terminal yet it becomes real easy. For example this deletes and then immediately restores a branch named master2:

user@MY-PC /C/MyRepo (master)
$ git branch -D master2
Deleted branch master2 (was 130d7ba).    <-- This is the SHA1 we need to restore it!

user@MY-PC /C/MyRepo (master)
$ git branch master2 130d7ba