首页 文章

如何将当前更改提交到git中的不同分支[重复]

提问于
浏览
558

这个问题在这里已有答案:

有时我会在工作目录中进行一些更改,并且我意识到这些更改应该在与当前更改的分支中提交 . 这通常发生在我想尝试新事物或进行一些测试时,我忘记事先创建一个新分支,但我不想将脏代码提交给主分支 .

所以, how can I make that uncommitted changes (or changes stored in the index) be committed to a different branch than the current one?

3 回答

  • 823

    您可以创建一个新分支并切换到它 . 然后提交您的更改:

    git branch dirty
    git checkout dirty
    // And your commit follows ...
    

    或者,您也可以签出现有分支(仅 git checkout <name> ) . 但只是,如果没有冲突(所有已编辑文件的基础与当前分支中的相同) . 否则你会收到一条消息 .

  • 19

    其他答案建议检查另一个分支,然后承诺,只有在可以通过本地修改结账时才能工作 . 如果没有,您处于 git stash 的最常见用例:

    git stash
    git checkout other-branch
    git stash pop
    

    第一个 stash 隐藏了您的更改(基本上是进行临时提交),随后 stash pop 重新应用它们 . 这让git使用它的合并功能 .

    如果当您尝试弹出存储时,会遇到合并冲突......接下来的步骤取决于这些冲突是什么 . 如果所有隐藏的更改确实属于另一个分支,那么您只需要对它们进行排序 - 这是因为您在错误的分支上进行了更改 .

    另一方面,如果你真的搞砸了,你的工作树有两个分支的混合变化,并且冲突只是你想要在原始分支上提交的那些,你可以节省一些工作 . 像往常一样,有很多方法可以做到这一点 . 这是一个,从弹出并看到冲突后开始:

    # Unstage everything (warning: this leaves files with conflicts in your tree)
    git reset
    # Add the things you *do* want to commit here
    git add -p     # or maybe git add -i
    git commit
    # The stash still exists; pop only throws it away if it applied cleanly
    git checkout original-branch
    git stash pop
    # Add the changes meant for this branch
    git add -p 
    git commit
    # And throw away the rest
    git reset --hard
    

    或者,如果您事先意识到这将会发生,只需提交属于当前分支的内容即可 . 您可以随时返回并修改该提交:

    git add -p
    git commit
    git stash
    git checkout other-branch
    git stash pop
    

    当然,请记住,这一切都需要一些工作,并且下次可以避免它,可能通过在您的bashrc中将 $(__git_ps1) 添加到PS1中,将当前分支名称添加到提示中 . (例如参见Git in Bash docs . )

  • 51
    • git checkout my_other_branch

    • git add my_file my_other_file

    • git commit -m

    并提供您的提交消息 .

相关问题