How to commit my current changes to a different branch in git
This question already has an answer here:
The other answers suggesting checking out the other branch, then committing to it, only work if the checkout is possible given the local modifications. If not, you're in the most common use case for git stash
:
git stash
git checkout other-branch
git stash pop
The first stash
hides away your changes (basically making a temporary commit), and the subsequent stash pop
re-applies them. This lets git use its merge capabilities.
If when you try to pop the stash, you run into merge conflicts... the next steps depend on what those conflicts are. If all the stashed changes indeed belong on that other branch, you're simply going to have to sort through them - it's a consequence of having made your changes on the wrong branch.
On the other hand, if you've really messed up, and your work tree has a mix of changes for the two branches, and the conflicts are just in the ones you want to commit back on the original branch, you can save some work. As usual, there are a lot of ways to do this. Here's one, starting from after you pop and see the conflicts:
# 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
Alternatively, if you realize ahead of the time that this is going to happen, simply commit the things that belong on the current branch. You can always come back and amend that commit:
git add -p
git commit
git stash
git checkout other-branch
git stash pop
And of course, remember that this all took a bit of work, and avoid it next time, perhaps by putting your current branch name in your prompt by adding $(__git_ps1)
to your PS1 in your bashrc. (See for example the Git in Bash docs.)
You can just create a new branch and switch onto it. Commit your changes then:
git branch dirty
git checkout dirty
// And your commit follows ...
Alternatively, you can also checkout an existing branch (just git checkout <name>
). But only, if there are no collisions (the base of all edited files is the same as in your current branch). Otherwise you will get a message.
git checkout my_other_branch
git add my_file my_other_file
git commit -m
并提供您的提交信息。
链接地址: http://www.djcxy.com/p/22454.html上一篇: 我如何获取我没有的分支的未合并拉取请求?