使用 git 将提交从 master 移动到分支
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3719068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Move commits from master onto a branch using git
提问by Paul
I'm trying to learn how to use Git effectively and I'm wondering how I should (good practice/bad practice?) solve the following case:
我正在尝试学习如何有效地使用 Git,我想知道我应该如何(好的做法/不好的做法?)解决以下情况:
Say I have the following chain of commits in master:
假设我在 master 中有以下提交链:
- Initial commit
- Commit 1
- Commit 2
- Commit 3
- 初始提交
- 提交 1
- 提交 2
- 提交 3
Then I realize that what's done in the last two commits is completely wrong and I need to start from Commit 1 again. Questions:
然后我意识到在最后两次提交中所做的完全错误,我需要再次从提交 1 开始。问题:
- How should I do that?
- Can I move Commit 2 and 3 to a separate branch to keep for future reference (say they weren't that bad after all) and continue working from Commit 1 on master?
- 我该怎么做?
- 我可以将 Commit 2 和 3 移动到一个单独的分支以供将来参考(说它们毕竟还不错)并继续在 master 上从 Commit 1 开始工作吗?
回答by VonC
git branch tmp # mark the current commit with a tmp branch
git reset --hard Commit1 # revert to Commit1
The SO answer "What's the difference between 'git reset' and 'git checkout' in git?" is quite instructive for that kind of operation
SO 答案“ git 中的 'git reset' 和 'git checkout' 之间有什么区别?”对这种操作很有指导意义
A git reset --hard HEAD~2
would do the same thing (without needing to get back the SHA1 for Commit1
first).
Agit reset --hard HEAD~2
会做同样的事情(不需要先取回 SHA1 Commit1
)。
Since Commit2
and Commit3
are still reference by a Git ref (here a branch), you can still revert to them anytime you want (git checkout tmp
).
由于Commit2
和Commit3
仍然被 Git 引用(这里是一个分支)引用,你仍然可以随时恢复到它们(git checkout tmp
)。
Actually, Darienmentions in the comments (regarding moving Commit2
and Commit3
to another branch):
实际上,Darien在评论中提到(关于移动Commit2
和Commit3
到另一个分支):
Accidentally committed to the wrong branch, this let me move it, did:
不小心提交到错误的分支,这让我移动它,做了:
git checkout correctbranch
git rebase tmp
git branch -d tmp
This works here since the initial branch has been reset to Commit1
, which means the git rebase tmp
will replay every commit after Commit1
(so here Commit2
and Commit3
) to the new 'correctbranch
'.
这在这里有效,因为初始分支已重置为Commit1
,这意味着git rebase tmp
将在Commit1
(因此在这里 Commit2
和Commit3
)之后重播每次提交到新的“ correctbranch
”。