Forgot to branch in git, need to move changes from master [duplicate]

拜拜、爱过 提交于 2019-12-04 15:27:41

问题


I eagerly ducked into code mode and modified some files, but neglected to branch from master first. The mods aren't so extensive that I can't redo them, but what's a good way of taking my (so far, uncommitted) changes in master and migrating them to a new branch, leaving master untouched in the end?


回答1:


If not yet committed anywhere (git status shows a bunch of stuff modified, it's OK if it's "git add"-ed too):

$ git checkout -b newbranch

Despite the name checkout this usage (with -b) does not check anything out. The -b flag says "create a new branch", so git creates the branch-name and makes it correspond to the current HEAD commit. Then it makes HEAD point to the new branch, and stops there.

Your next commit is therefore on newbranch, which has as its parent commit, the commit you were on when you started modifying files. So assuming you were on master, and you had these commits:

A - B - C       <-- HEAD=master

the checkout -b makes this read:

A - B - C       <-- master, HEAD=newbranch

and a later commit adds a new commit D:

A - B - C       <-- master
          \
            D   <-- newbranch



回答2:


git branch -M master my-branch

and then

git fetch origin refs/heads/master:refs/heads/master

or

git branch master my-branch  (or another ref)



回答3:


git stash
git stash branch <branchname>


来源:https://stackoverflow.com/questions/19612439/forgot-to-branch-in-git-need-to-move-changes-from-master

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!