tags:

views:

172

answers:

3

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?

+1  A: 
  1. git checkout my_other_branch
  2. git add my_file my_other_file
  3. git commit -m

And provide your commit message.

Hank Gay
you may want to write what *co* and *ci* is ... though one can guess it (checkout, commit) ^^
tanascius
@tanascius Good suggestion, and done. I've been using the aliases so long I forget they aren't the default.
Hank Gay
+5  A: 

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 ...

You can checkout an existing branch without any more effort, too (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.

tanascius
Note that in the case of switching to **existing** ***divergent*** branch you can use `-m` option to tell git to try to merge changes, i.e. `git checkout -m <name>`
Jakub Narębski
+5  A: 

The two current answers (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 second re-applies them. This lets git use its merge capabilities.

Jefromi