I've been working on a project, but unfortunately, I forgot to switch to my br开发者_Go百科anch, 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?
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.
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.
git stash
is what you need.
a full explanation can be found in Git-Tools-Stashing
As it is possible to create a new branch but not possible to checkout an existing branch while having files checked out, I found the following trick using a temporary branch to work:
This scenario works at least with VS 2015 Git plugin but would most likely work with any git tool.
- checkout and make changes to files in master (ups!, wrong branch)
- create a new branch "temp" (or any unused name you choose) from master. Checked out files will now be checked out in temp and not in master.
- check in changes to temp (master is untouched)
- Everything is now checked in and it is possible to check out an existing branch. Check out the wanted branch (the branch I wanted to make the changes to begin with) 3.5 Git Rebase
- merge temp to the wanted branch. Now the changes are in the correct branch.
- delete the temp branch as it is not needed any more
EDIT: I found out that you will have to perform a rebase (git rebase --onto) of the temp branch before performing the merge. Otherwise the changes in master will be included in the merge. An extra step 3.5 above. See further about rebase here: https://git-scm.com/book/en/v2/Git-Branching-Rebasing
Github Desktop
In Github Desktop, when creating a new branch or moving to a different branch with uncommitted changes, you will be asked if you want to leave the changes or move them to the new branch:
精彩评论