乐闻世界logo
搜索文章和话题

Git 如何将最近的提交移动到新的分支?

2个答案

1
2

对于那些想知道它为什么有效的人

您想返回 C,并将 D 和 E 移动到新分支。

一开始看起来是这样的:

shell
A-B-C-D-E (HEAD) master

git branch newBranch

shell
newBranch A-B-C-D-E (HEAD) master

git reset --hard HEAD~2

shell
newBranch A-B-C-D-E (HEAD) master

由于分支只是一个指针,因此_master指向最后一次提交。当您创建newBranch_时,您只需创建一个指向最后一次提交的新指针。然后使用 git reset您将_主_指针移回两个提交。但由于您没有移动_newBranch_,它仍然指向它最初所做的提交。

2024年6月29日 12:07 回复

还有另一种方法可以做到这一点,只需使用 2 个命令。还可以保持您当前的工作树完好无损。

shell
git checkout -b newbranch # switch to a new branch git branch -f master HEAD~3 # make master point to some older commit

旧版本- 在我了解之前git branch -f

shell
git checkout -b newbranch # switch to a new branch git push . +HEAD~3:master # make master point to some older commit

能够push做到这一点.是一个很好的技巧。

2024年6月29日 12:07 回复

你的答案