Git undo local branch delete

2019-01-09 22:15发布

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

How do I recover the branch?

6条回答
太酷不给撩
2楼-- · 2019-01-09 22:31

Thanks, this worked.

git branch new_branch_name sha1

git checkout new_branch_name

//can see my old checked in files in my old branch

查看更多
一纸荒年 Trace。
3楼-- · 2019-01-09 22:33

First: back up your entire directory, including the .git directory.

Second: You can use git fsck --lost-found to obtain the ID of the lost commits.

Third: rebase or merge onto the lost commit.

Fourth: Always think twice before using -D or --force with git :)

You could also read this good discussion of how to recover from this kind of error.

EDIT: By the way, don't run git gc (or allow it to run by itself - i.e. don't run git fetch or anything similar) or you may lose your commits for ever.

查看更多
仙女界的扛把子
4楼-- · 2019-01-09 22:38

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 
查看更多
来,给爷笑一个
5楼-- · 2019-01-09 22:43

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 here.

查看更多
可以哭但决不认输i
6楼-- · 2019-01-09 22:43

If you haven't push the deletion yet, you can simply do :

$ git checkout deletedBranchName
查看更多
老娘就宠你
7楼-- · 2019-01-09 22:46

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
查看更多
登录 后发表回答