Git - working on wrong branch - how to copy changes to existing topic branch

I've been working on a project, but unfortunately, I forgot to switch to my branch, and as such have been working on master

How can I copy the work (3 files) I've done here from master, to my branch (called, for example branch123) without comitting to master?


Solution 1:

Sounds like all you need is the following:

git stash
git checkout branch123
git stash apply

Then you should be back on your own branch without touching the master branch.

Solution 2:

The accepted answer is the most thorough, but there is a special case where you can simplify. If the files you have modified in the working directory are identical in both master and branch123 you can simply do

git checkout branch123

No need to stash anything, since the default behavior of checkout is to NOT overwrite modified files in your working directory, so you won't lose anything. (This was actually mentioned in the comments first by Cascabel)

As other people have mentioned in the comments, if branch123 doesn't exist yet, you can do

git checkout -b branch123

Based on what I found here.