在 Git 中删除分支后可以恢复吗?
如果我运行 gitbranch -d XYZ ,有没有办法恢复分支?有没有办法像我没有运行删除分支命令一样返回?
If I run git branch -d XYZ
, is there a way to recover the branch? Is there a way to go back as if I didn't run the delete branch command?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(26)
首先
在终端中输入。
之后,获取
HEAD@{**number**}
(例如HEAD@{12}
)。现在输入:
First type
in the terminal.
After that, get the
HEAD@{**number**}
(e.g.HEAD@{12}
).Now enter:
添加到 tfe答案:还有 git-resurrect.sh
contrib/ Git 源代码区域(在 git.git 存储库中),这可能会对您有所帮助。
Adding to tfe answer: there is also the git-resurrect.sh script in the
contrib/
area of the Git sources (in git.git repository), which might help you.我使用以下命令来查找并检索已删除的分支。第一步来自 gcb 的描述。
现在根据提交注释查找 git 提交 ID (GIT-SHA) 并在下面的命令中使用它。使用之前找到的 GIT-SHA 检查一个名为 NEW-BRANCH 的新分支:
I used the following commands to find and retrieve my deleted branch. The first steps are from gcb's description.
Now look for the git commit id (GIT-SHA) based on the commit comments and use it in the command below. Checkout a new branch called NEW-BRANCH with the previously found GIT-SHA:
谢谢大家。
我的问题是我删除了 GitLab(远程)和 GIT(本地)上的分支。
但不知怎的,我像这样拿回了我的提交:
然后我拿回了我的提交我推送了分支感谢
上帝。
ps:不知何故(SHA)是提交代码
Thanks for all of you.
My problem was that i deleted my branch on GitLab (remotely) as well as on GIT (locally).
but somehow i got my commits back like so:
Then i got my commits back i pushed the branch all over again
Thank god.
ps: Somehow (SHA) is a commit code
如果您没有重新记录,例如。因为您正在一个未启用引用日志的裸存储库中工作,并且您要恢复的提交是最近创建的,所以另一个选择是查找最近创建的提交对象并查看它们。
从
.git/objects
目录中运行:这会查找过去 12 小时内创建的所有对象(提交、文件、标签等)并过滤它们以仅显示提交。检查这些是一个快速的过程。
不过,我会首先尝试Jakub的答案中提到的 git-ressurect.sh 脚本。
If you don't have a reflog, eg. because you're working in a bare repository which does not have the reflog enabled and the commit you want to recover was created recently, another option is to find recently created commit objects and look through them.
From inside the
.git/objects
directory run:This finds all objects (commits, files, tags etc.) created in the last 12 hours and filters them to show only commits. Checking these is then a quick process.
I'd try the git-ressurect.sh script mentioned in Jakub's answer first though.
据我了解,如果要删除的分支可以被另一个分支访问,您可以使用安全地删除它
,并且您的工作不会丢失。请记住,分支不是快照,而是指向快照的指针。因此,当您删除分支时,您也会删除一个指针。
如果您删除另一个分支无法访问的分支,您甚至不会丢失工作。当然,这不像检查提交哈希那么容易,但您仍然可以做到。这就是为什么 Git 无法删除使用
-d
无法到达的分支。相反,你必须使用这是 Scott Chacon 的有关 Git 的必看视频的一部分。查看 58:00 分钟,他谈论分支以及如何删除它们。
GitHub 的 Scott Chacon 介绍 Git
From my understanding if the branch to be deleted can be reached by another branch, you can delete it safely using
and your work is not lost. 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. Of course it won't be as easy as checking out the commit hash, but you can still do it. That's why Git is unable to delete a branch which cannot be reached by using
-d
. Instead you have to useThis is part of a must watch video from Scott Chacon about Git. Check minute 58:00 when he talks about branches and how delete them.
Introduction to Git with Scott Chacon of GitHub
对于未安装 Git 的 GitHub 用户:
如果您想从<恢复它a href="https://github.com/Maxim-Mazurok" rel="nofollow noreferrer">GitHub 网站,您可以使用他们的 API 获取与 repo 相关的列表事件:
首先
找到那些 SHA(提交哈希值):
curl -i https://api.github.com/repos/PublicUser/PublicRepo/events
...或私人仓库:
curl -su YourUserName https://api.github.com/repos/YourUserName/YourProject/events
(将提示输入 GitHub 密码)
下一步
• 转至分支并删除该分支。
• 在同一页面上,无需重新加载,打开 DevTools、网络面板。现在准备...
• 单击恢复。您会注意到一条新的“线”。右键单击它并选择“复制为 cURL”并将此文本保存在某个编辑器中。
• 附加到复制的代码行的末尾,这一个:
-H "Cookie="
。您现在应该得到类似的结果:
最后一步
PS
我意识到这可能不是“最简单的解决方案”或“正确的”解决方案,但提供它是为了以防万一有人发现它有用。
For GitHub users without Git installed:
If you want to restore it from GitHub website, you can use their API to get a list of repo-related events:
First
find those SHAs (commit hashes):
curl -i https://api.github.com/repos/PublicUser/PublicRepo/events
... or for private repos:
curl -su YourUserName https://api.github.com/repos/YourUserName/YourProject/events
(will be prompted for GitHub password)
Next
• Go to branches and delete that one.
• On the same page, without reloading, open DevTools, Network panel. Now prepare...
• Click restore. You will notice a new "line". Right-click on it and select "Copy as cURL" and save this text in some editor.
• Append to the end of the copied line of code, this one:
-H "Cookie="
.You should now get something like:
Final step
P.S.
I realize this may not be the "simplest solution" or the "right" solution, but it is offered in case someone finds it useful.
确保在本地执行所有这些操作,并在推送到 Bitbucket Cloud 之前确认您的存储库处于您想要的状态。克隆当前存储库并首先测试这些解决方案也可能是个好主意。
2.要恢复分支,请使用:
如果您不知道“sha”,您可以:
如果您的提交不在引用日志中:
2.然后,您可以使用以下命令之一显示每个提交:
Make sure to perform all of this locally, and confirm your repo is in the state you desire before pushing to Bitbucket Cloud. It may also be a good idea to clone your current repo, and test these solutions out first.
2.To restore the branch, use:
If you don't know the 'sha' off the top of your head, you can:
If your commits are not in your reflog:
2.You can then display each commit using one of these:
要恢复已删除的分支,首先要查看引用日志历史记录,
其中 n 指的是最后 n 次提交。然后找到合适的头并用该头创建一个分支。
For recovering a deleted branch, First go through the reflog history,
Where n refers to the last n commits. Then find the proper head and create a branch with that head.
我从远程重新建立了一个分支,尝试清除一些我不想要的提交,并打算挑选我想要的正确的提交。当然,我写的 SHA 是错误的...
这是我找到它们的方法(主要是这里答案中的一个更简单的界面/交互):
首先,在日志中生成松散提交的列表。尽快执行此操作并停止工作,因为这些可能会被垃圾收集器倾倒。
这将创建一个
lost
文件,其中包含您必须查看的所有提交。为了简化我们的生活,让我们只从中删除 SHA:现在您有一个
commits
文件,其中包含您必须查看的所有提交。假设您使用的是 Bash,最后一步:
这将向您显示每个文件的差异和提交信息。然后等待您按 Enter。现在写下您想要的所有内容,然后将它们挑选出来。完成后,只需按 Ctrl-C 即可。
I rebased a branch from remote to try to clear a few commits I didn't want and was going to cherrypick the right ones that I wanted. Of course I wrote the SHAs wrong...
Here is how I found them (mostly an easier interface/interaction from things on answers here):
First, generate a list of loose commits in your log. Do this as soon as possible and stop working, as those may be dumped by the garbage collector.
This creates a
lost
file with all the commits you will have to look at. To simplify our life, let's cut only the SHA from it:Now you have a
commits
file with all the commits you have to look.Assuming you are using Bash, the final step:
This will show you the diff and commit information for each of them. And wait for you to press Enter. Now write down all the ones you want, and then cherry-pick them in. After you are done, just Ctrl-C it.
恢复已删除分支的一般问题的一个非常常见的子问题是在合并后恢复功能分支,然后将其删除 - 这是常见的做法。
正如这篇 SO post 所涵盖的那样,您始终可以恢复已删除的分支,如果它已经合并成功。这是因为分支只是指向提交的奇特指针,并且因为您已经合并,所以提交仍然存在。合并提交将列出两个(或更多)合并分支的头提交的哈希值。例如:
因此您可以通过执行 git checkout -b feature 97f8a60 来恢复删除的“feature”分支 - 不需要任何引用日志内容。
A very common sub problem of the general problem of recovering deleted branches is recovering a feature branch after merging and then deleting it - as is common practice.
As this SO post covers you can always recover a deleted branch if it has been merged successfully. This is because a branch is just a fancy pointer to a commit and because you've merged, the commit is still there. A merge commit will list the hash of the head commits of the two (or more) branches merged. For example:
So you can recover the delete 'feature' branch by doing
git checkout -b feature 97f8a60
- no need for any reflog stuff.我在删除分支的计算机上执行了此操作:
git reflog
响应:
并使用以下命令检索分支:
git checkout -b newBranchName 74b2383
I did this on the computer which i delete the branch:
git reflog
response:
and i retrieve the branch with this command:
git checkout -b newBranchName 74b2383
如果您正在使用 GitHub(我假设这里的绝大多数读者都是如此),那么您可以按照以下三个步骤操作,不需要命令行访问:
If you're using GitHub (which I'm assuming the vast majority of readers here are), then you can follow these three steps that doesn't require command-line access:
BIG YES
如果你使用 GIT
按照这些简单的步骤操作
https://confluence.atlassian .com/bbkb/how-to-restore-a-deleted-branch-765757540.html
如果您正在使用 smartgit 并已经推送该分支
转到原点,找到该分支并右键单击然后结帐
BIG YES
if you are using GIT
follow these simple steps
https://confluence.atlassian.com/bbkb/how-to-restore-a-deleted-branch-765757540.html
if you are using smartgit and already push that branch
go to origin, find that branch and right click then checkout
如果您正在使用 Git 扩展
虽然很旧,但当您在 google 上搜索恢复已删除的分支时,此线程位于列表的顶部。我使用 git 扩展而不是命令行,所以不熟悉这些命令,但是 reflog 命令给了我一个线索,所以我在这里发布我的 git 扩展解决方案,供其他使用 git 扩展的人使用读这个。
您删除的分支现在应该可以查看和选择,只需单击它并查看即可。
If you are using Git Extensions
Although old, this thread is the top of the list when you google recovering deleted branches. I use git extensions rather than the command line and so am unfamiliar with the commands but the reflog command gave me a clue so I'm posting my git extensions solution here for others that are using git extensions who may read this.
Your deleted branch should now be viewable and selectable, simply click on it and check it out.
首先转到 git 批处理移动到您的项目,如下所示:
您都有一个更改列表,并且参考号采用参考号,然后从 android studio 或 git betcha 结帐。
另一个解决方案是获取参考号并转到 android studio,单击 git 分支,然后单击结帐标签或修订版参考号,然后哈哈,您就拥有了分支。
First go to git batch the move to your project like :
You all have a list of the changes and the reference number take the ref number then checkout
from android studio or from the git betcha.
another solution take the ref number and go to android studio click on git branches down then click on checkout tag or revision past the reference number then lol you have the branches.
添加到 tfe 的答案中,您可以使用提到的此过程进行恢复,除非它的提交未被垃圾收集。 Git 分支只是指向提交树中特定提交的指针。但是,如果您删除指针,并且该分支上的提交未合并到其他现有分支中,则 git 会将其视为悬空提交,并在垃圾收集期间删除它们,垃圾收集可能会定期自动运行。
如果您的分支没有合并到现有分支,并且它被垃圾收集,那么您将丢失所有提交,直到分支从现有分支分叉的点为止。
Adding to tfe's answer, you can recover with this process mentioned, unless it's commits are not garbage collected. Git branch is simply a pointer to a particular commit in the commit tree. But if you delete the pointer, and the commits on that branch are not merged into other existing branch, then git treats it as dangling commits and removes them during garbage collection, which it may run automatically periodically.
If your branch wasn't merged to an existing branch, and if it was garbage collected, then you will loose all commits up until the point from where branch was forked from an existing branch.
仅使用 git reflog 并没有为我返回 sha 。
只有
commit id
(8个字符长,sha更长)所以我使用
git reflog --no-abbrev
然后执行与上面相同的操作:
git checkout -b <分支>
Just using
git reflog
did not return thesha
for me.Only the
commit id
(which is 8 chars long and a sha is way longer)So I used
git reflog --no-abbrev
And then do the same as mentioned above:
git checkout -b <branch> <sha>
如果您使用 VSCode...并且您在删除分支之前的某个时刻将分支与服务器同步...
请注意,gitbranchdelete 仅删除本地副本,而不是服务器上的副本。首先,在 Git 面板(左侧工具栏上的 git 图标)中,查看分支并查看您的分支是否仍在“origin/your_branch_name”下。如果是这样,只需选择它,您就应该取回代码(建议您立即将其复制/粘贴/保存在本地其他位置)。
如果您没有看到“origin/your_branch_name”,请安装 GitLens 扩展。这使您可以直观地浏览服务器存储库并找到同步到服务器的副本。如果您有多个存储库,请注意,可能需要从所需存储库中至少打开一个文件才能使该存储库出现在 GitLens 中。然后:
打开 GitLens 面板
展开存储库
您应该看到类别列表:分支/贡献者/远程/存储/等
您应该在“分支”下或可能在“远程 -> 起源”下找到 YourLostTreasure。希望您会看到一个具有所需名称的分支 - 如果展开它,您应该会看到您在该分支中更改的文件。双击文件名将其打开,并立即备份该代码。
如果您没有立即看到丢失的分支,请四处查看,如果发现有希望的内容,请立即打开它并获取代码。我不得不四处寻找,直到找到 TheGoldenBranch,即使这样,代码也丢失了最后一两次保存(可能是因为我在尝试分支合并之前未能同步到服务器,但意外地单击了 -分支删除)。我的搜索不必要地延长了,因为当我第一次找到该分支时,我并不完全确定该名称是否正确,因此一直在寻找,并且花了一些时间才重新找到第一个分支。 (因此,Carpe Carpum 和 然后 继续寻找。)
IF you are using VSCode... and you synced your branch with the server at some point before deleting it...
Note that git branch delete only deletes the local copy, not the copy on the server. First, in the Git panel (git icon on left toolbar), look through the branches and see if your branch is still there under "origin/your_branch_name". If so, just select that and you should get your code back (suggest that you immediately copy/paste/save it locally somewhere else).
If you didn't see an "origin/your_branch_name", Install the GitLens extension. This allows you to visually poke around in the server repositories and locate the copy you synced to the server. If you have multiple repositories, note that it might be necessary to have at least one file opened from the desired repository in order to make the repository appear in GitLens. Then:
Open the GitLens panel
Expand the repository
You should see a list of categories: Branches / Contributors / Remotes / Stashes / etc
You should find YourLostTreasure under "Branches" or possibly under "Remotes -> Origins". Hopefully, you will see a branch with the desired name - if you expand it, you should see the files you changed in that branch. Double-click the file names to open them, and immediately back up that code.
If you don't immediately see your lost branch, poke around and if you find something promising, immediately open it and grab the code. I had to poke around quite a bit until I found TheGoldenBranch, and even then the code was missing the last one or two saves (possibly because I failed to sync to server before attempting-a-Branch-Merge-but-accidentally-clicking-Branch-Delete). My search was unnecessarily lengthened because when I first found the branch I wasn't completely sure the name was correct so kept looking, and it took some time to re-find that first branch. (Thus, Carpe Carpum and then keep looking.)
如果您已经将分支推送到远程服务器,请尝试使用 git checkout,git 将尝试从本地计算机中的最后一个原始镜像进行克隆。
If you already push branch to remote server then try to use
git checkout <branch>
and git will try to clone from you're last origin mirror in your local machine.您可以像下面一样在 ADO 中搜索,然后单击“恢复”
You can search in ADO like below and click on 'restore'
是的,您应该能够执行 git reflog --no-abbrev 并在已删除分支的顶部找到提交的 SHA1,然后只需 git checkout [sha] 。一旦您完成该提交,您只需 git checkout -b [branchname] 即可从那里重新创建分支。
感谢@Cascabel提供了这个压缩/单行版本,感谢@Snowcrash了解了如何获取sha。
如果您刚刚删除了分支,您将在终端中看到类似的内容
已删除分支(是)
。然后只需在这段代码中使用
即可:Yes, you should be able to do
git reflog --no-abbrev
and find the SHA1 for the commit at the tip of your deleted branch, then justgit checkout [sha]
. And once you're at that commit, you can justgit checkout -b [branchname]
to recreate the branch from there.Credit to @Cascabel for this condensed/one-liner version and @Snowcrash for how to obtain the sha.
If you've just deleted the branch you'll see something like this in your terminal
Deleted branch <your-branch> (was <sha>)
. Then just use that<sha>
in this one-liner:(重新)创建分支一旦获得提交哈希,
您将使用此命令在指定的提交哈希上创建新分支:
但是最难的部分是找到提交哈希,您将有 2下面解释了选项:
使用命令行查找提交哈希
当提交哈希位于
reflog
中时 大多数情况下,无法访问的提交位于
reflog
中(跟踪大量 git 更改)。因此,首先要尝试的是使用命令git reflog
查看引用日志(该命令显示HEAD
的引用日志)。如果提交是特定且仍然存在的分支的一部分,也许更简单的方法是使用命令 git reflog name-of-my-branch 。它也可以与远程一起使用,例如,如果您强制推送(尽管应该使用 git push --force-with-lease 来代替,这样可以防止错误并且更容易恢复)。
当提交哈希不在
reflog
中时如果您的提交不在您的reflog中(可能它们被不写入reflog的第三方工具删除),您可以先尝试此命令创建一个包含所有悬空提交的文件
,然后读取丢失提交的 SHA 并将您的分支重置到它。
频繁的用户可能会使用创建别名
git saving
以下是一些示例,展示如何分析找到的提交
显示提交元数据(作者、创建日期和提交消息):
另请参阅差异:
在找到的内容上创建分支提交:
在 Windows 上使用 GitExtensions GUI
与从命令行执行的操作类似,您可以进行提交来自引用日志或悬挂提交的哈希:
来自引用日志(要尝试的第一件事)
您有 2 个选项:
在修订网格中显示悬挂提交(也许是最简单的):在菜单中
查看
=>显示引用日志引用
,您现在应该能够看到引用日志中的悬空提交(灰色分支,尖端没有分支/引用标签:复制提交哈希)访问 HEAD 或其他分支的引用日志内容:在菜单
Commands
=> 中显示引用日志...
从引用日志中查找不可用丢失的提交
您可以通过菜单
Repository
=> 恢复丢失的提交(以及未提交的暂存文件!)Git 维护
=>恢复丢失的对象...
。对于按日期排序的每个提交,您将获得哈希值、提交消息,并且能够轻松显示提交差异。相关:轻松恢复之前已暂存但未提交的已删除/丢失的文件
(Re)Creating the branch ONCE you've got the commit hash
You will do it use this command to create the new branch on the specified commit hash:
But the hardest part is to find the commit hash and you will have 2 options explained just below:
Finding the commit hash with the command line
When the commit hash is in the
reflog
Most of the time unreachable commits are in the
reflog
(that keeps track of a lot of git changes). So, the first thing to try is to look at the reflog using the commandgit reflog
(which displays the reflog forHEAD
).Perhaps something easier is to use the command
git reflog name-of-my-branch
if the commit was part of a specific and still existing branch. It also works with a remote e.g. if you had force pushed (though one should usegit push --force-with-lease
instead which prevents mistakes and is more recoverable).When the commit hash is NOT in the
reflog
If your commits are not in your reflog (perhaps they were deleted by a 3rd party tool that doesn't write to the reflog), you may try this command first to create a file with all the dangling commits
then read the SHA of the missing commit and reset your branch to it.
Frequent users may create the alias
git rescue
usingHere are some examples showing how to analyze the found commits
Display commit metadata (author, creation date and commit message):
Also see diffs:
Create a branch on the found commit:
Using GitExtensions GUI on Windows
Similarly to what you can do from the command line, you can take the commit hash from the reflog or from dangling commits:
From the reflog (1st thing to try)
You have 2 options:
Display dangling commits in the revision grid (maybe the easiest): In the menu
View
=>Show reflog references
and you should now be able to see the dangling commits from the reflogs (the branch in grey with no branch/reference label at the tip: copy the commit hash)Access to reflog content for HEAD or another branch: In the menu
Commands
=>Show reflogs...
Finding a lost commit not available from the reflog
You can recover lost commits ( and also uncommitted staged files!) with via the menu
Repository
=>Git maintenance
=>Recover lost objects...
. For each commit, sorted by date, you will have the hash, the commit message and will be able to display easily the commit diff.Related: Easily recover deleted/lost files that have been staged previously but not committed
如果您喜欢使用 GUI,则可以使用 gitk 执行整个操作。
这将允许您查看分支的提交历史记录,就像分支尚未被删除一样。现在,只需右键单击分支的最新提交,然后选择菜单选项
创建新分支
。If you like to use a GUI, you can perform the entire operation with gitk.
This will allow you to see the branch's commit history as if the branch hadn't been deleted. Now simply right click on the most recent commit to the branch and select the menu option
Create new branch
.投票最高的解决方案实际上比要求的要多:
或者
将您连同您可能忘记提交的所有最近更改一起移至新分支。这可能不是您的意图,尤其是在丢失分支后处于“恐慌模式”时。
一个更干净(更简单)的解决方案似乎是一句简单的话(在您使用
git reflog
找到
之后):现在您当前的分支和未提交的更改都不会受到影响。相反,只会创建一个新分支,一直到
。如果不是提示,它仍然可以工作,并且您会得到一个较短的分支,然后您可以使用新的
和新的分支名称重试,直到正确为止。最后,您可以将成功恢复的分支重命名为它原来的名称或其他任何名称:
不用说,成功的关键是找到正确的提交
,因此请明智地命名您的提交:)The top voted solution does actually more than requested:
or
move you to the new branch together with all recent changes you might have forgot to commit. This may not be your intention, especially when in the "panic mode" after losing the branch.
A cleaner (and simpler) solution seems to be the one-liner (after you found the
<sha>
withgit reflog
):Now neither your current branch nor uncommited changes are affected. Instead only a new branch will be created all the way up to the
<sha>
.If it is not the tip, it'll still work and you get a shorter branch, then you can retry with new
<sha>
and new branch name until you get it right.Finally you can rename the successfully restored branch into what it was named or anything else:
Needless to say, the key to success was to find the right commit
<sha>
, so name your commits wisely :)如果您删除了分支并忘记了其提交 ID,您可以执行以下命令:
此后,您将能够看到所有提交。
然后,您可以对此 id 执行 git checkout 并在此提交下创建一个新分支。
If you removed the branch and forgot its commit id, you can do this command:
After this, you'll be able to see all commits.
Then, you can do
git checkout
to this id and under this commit create a new branch.