3

I have two branches, say B1 and B2. I'm in B2 and I have staged and unstaged files.

I want the staged files to be committed in B1 (I thought I was in B1 when I git add-ed the files) and the unstaged ones to be committed in B2.

Is it possible? How?

gregseth
  • 12,952
  • 15
  • 63
  • 96

3 Answers3

3

I'm sure there's a more elegant way but all I could come up with is:

  1. Commit staged files to B2
  2. Stash the unstaged work on B2
  3. Switch to B1, then cherry-pick the latest commit of B2 in B1
  4. Switch back to B2, reset the latest commit (--hard way)
  5. Stage and commit the stashed work on B2

EDIT

This question has a detailed answer that does more or less what I've suggested.

Community
  • 1
  • 1
aefxx
  • 24,835
  • 6
  • 45
  • 55
3

git stash is really powerful when it comes to move dirty changes between branches. In your case, you can apply these steps:

  1. git stash --keep-index, this will stash only unstaged files
  2. git stash, this will stash the rest, i.e. staged files
  3. switch to B1
  4. git stash pop, staged files will be moved to B1
  5. switch to B2
  6. git stash pop, unstaged files will be moved to B2

After that, you can commit the changes in each branch individually.

ogzd
  • 5,532
  • 2
  • 26
  • 27
1

If the modfied staged and unstaged files does not change by switching to branch B1, you can switch branches without affecting anything, then you can easily commit your files and switch back to B2.

However if your modified files are changed between B1 and B2, you cannot switch branches. In this case, you have to stash your changes before swithcing branches.

  1. git stash --keep-index to stash and keep staged files
  2. git reset HEAD to unstage staged files
  3. git stash to stash your previousely staged files
  4. git checkout B1 to switch to B1 branch
  5. git stash pop to unstash and remove your last stash
  6. git commit -a to commit your previousely staged files on B1
  7. git checkout B2 to switch to B2 branch
  8. git stash pop
  9. git commit -a commit all the remaining changes on B2

Be carefull with these commands! I'm not a git pro! :-)

Mohammad Dehghan
  • 17,853
  • 3
  • 55
  • 72