简体   繁体   English

使用git将提交从master移到分支上

[英]Move commits from master onto a branch using git

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 承诺1
  • Commit 2 承诺2
  • Commit 3 承诺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. 然后我意识到在最后两次提交中完成的操作是完全错误的,我需要再次从Commit 1开始。 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? 我可以将Commit 2和3移动到一个单独的分支以备将来参考(毕竟它们并不是那么糟糕)并继续在master上使用Commit 1吗?
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). 一个git reset --hard HEAD~2会做同样的事情(不需要先为Commit1取回SHA1)。

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 ). 由于Commit2Commit3仍然由Git引用(这里是分支)引用,您仍然可以随时恢复它们( git checkout tmp )。


Actually, Darien mentions in the comments (regarding moving Commit2 and Commit3 to another branch): 实际上, Darien在评论中提到(关于将Commit2Commit3移动到另一个分支):

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 (所以这里是Commit2Commit3 )之后的每次提交重Commit3新的' correctbranch '。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM