使用 git 将提交从 master 移至分支
我正在尝试学习如何有效地使用 Git,我想知道我应该如何(好的做法/坏的做法?)解决以下情况:
假设我在 master 中有以下提交链:
- 初始提交
- 提交 1
- 提交 2
- 提交3
然后我意识到最后两次提交所做的事情是完全错误的,我需要再次从第一次提交开始。问题:
- 我应该怎么做?
- 我可以将提交 2 和 3 移动到一个单独的分支以供将来参考(假设它们毕竟没有那么糟糕)并继续从 master 上的提交 1 开始工作吗?
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:
Say I have the following chain of commits in master:
- Initial commit
- Commit 1
- Commit 2
- Commit 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:
- 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
SO答案““git”之间有什么区别git 中的“reset”和“git checkout”?”对于此类操作非常有指导意义
A
git reset --hard HEAD~2
会做同样的事情(不需要先取回Commit1
的 SHA1)。由于
Commit2
和Commit3
仍然由 Git 引用(此处为分支)引用,因此您仍然可以随时恢复到它们(git checkout tmp
)。实际上, Darien 在评论中提到了(关于移动
Commit2
和Commit3
到另一个分支):这在这里有效,因为初始分支已重置为
Commit1
,这意味着git rebase tmp
将重播Commit1
之后的每次提交(这里是Commit2
和Commit3
)到新的“Correctbranch
”。The SO answer "What's the difference between 'git reset' and 'git checkout' in git?" is quite instructive for that kind of operation
A
git reset --hard HEAD~2
would do the same thing (without needing to get back the SHA1 forCommit1
first).Since
Commit2
andCommit3
are still reference by a Git ref (here a branch), you can still revert to them anytime you want (git checkout tmp
).Actually, Darien mentions in the comments (regarding moving
Commit2
andCommit3
to another branch):This works here since the initial branch has been reset to
Commit1
, which means thegit rebase tmp
will replay every commit afterCommit1
(so hereCommit2
andCommit3
) to the new 'correctbranch
'.