Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git undo local branch delete

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

How do I recover the branch?

like image 226
Stefan Kendall Avatar asked Oct 26 '10 16:10

Stefan Kendall


3 Answers

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
like image 121
bobDevil Avatar answered Nov 15 '22 18:11

bobDevil


If you know the last SHA1 of the branch, you can try

git branch branchName <SHA1>

You can find the SHA1 using git reflog, described in the solution --defect link--.

like image 93
Chetan Avatar answered Nov 15 '22 19:11

Chetan


If you just deleted the branch, you will see something like this in your terminal:

Deleted branch branch_name(was e562d13)
  • where e562d13 is a unique ID (a.k.a. the "SHA" or "hash"), with this you can restore the deleted branch.

To restore the branch, use:

git checkout -b <branch_name> <sha>

for example:

git checkout -b branch_name e562d13 
like image 50
developerick Avatar answered Nov 15 '22 17:11

developerick