1

I’m still fairly new to the Git way of thinking, and I use it almost exclusively through the VSCode GUI and the Github desktop application, so bear with me if my thinking or terminology is backwards or sideways.

I frequently find myself in the situation that I do some work, then realise some of the work I’ve just done should have been done in a different branch than I’m in and need to move those changes to another branch. But this only applies to some of the changes in the current branch – the rest of the changes in the branch do belong where they are and should stay put. Usually it’ll be just a small handful of files I want to move, while perhaps 40 or 50 files should stay where they are.

There are lots of questions and tutorials on how to change branches and move all your uncommitted changes to another branch; I can also find questions on how to cherry-pick from an existing commit (like this one – but Google as I might, I cannot find any descriptions of how to move only specific, selected, uncommitted changes to a different branch. That is,

  • the changes are not committed in the current branch (and I don’t want to commit them there, because they don’t belong in that branch)
  • the changes to move are only a subset of the total number of changes in the current branch
  • after the move, the changes should disappear from the current branch and be added to existing changes in the other branch so that I can commit them in that branch

I can cherry-pick the files manually (file by file) or I can stage or unstage the particular changes I want to move or not move; either way is fine with me (or if there’s another way, that’d be fine too).

Theoretically, I would imagine I should be able to stash the changes in current branch excluding the files I want to move, and then switch to the other branch. I’ve found a description of how to stash specific files, but not a way to do the opposite, stashing everything except specific files.

Is there some relatively simple way to accomplish this?

Janus Bahs Jacquet
  • 859
  • 1
  • 11
  • 27

1 Answers1

0

Of course, as always happens, a solution occurred to me right after posting here… Very possibly not the best or easiest way of doing it, but it works.

It can be done in a few, relatively simple steps combining staging and stashing:

  1. Stage the changes you want to bring over to the other branch
  2. Stash your unstaged changes with git stash -ku (k for keep-index, which limits it to unstaged changes, u for including untracked files)
  3. Switch to the branch you want and commit the changes there
  4. Switch back to the branch you were in and apply/pop your stash with git stash apply git stash pop

For reasons I don’t really understand, the staged changes also reappeared when I applied my stash, but since they were now committed in the other branch, I could just unstage and discard them in the current branch.

Janus Bahs Jacquet
  • 859
  • 1
  • 11
  • 27