Sometimes it happens that I make some changes in my working directory, and I realize that these changes should be committed in a branch different to the current one. This usually happens when I want to try out new things or do some testing and I forget to create a new branch beforehand, but I don't want to commit dirty code to the master branch.
So, how can I make that uncommitted changes (or changes stored in the index) be committed to a different branch than the current one?
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 environment variable in your bashrc file. (See for example the Git in Bash documentation.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With