Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

git

git-branch

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?

like image 452
larryq Avatar asked Oct 26 '13 22:10

larryq


People also ask

Do you lose changes if you switch branches?

No changing is required. If the hash IDs differ, the file is different in the two branches, and must be changed to switch branches. The key notion here is that files in commits are frozen forever. Files you will edit are obviously not frozen.


1 Answers

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 
like image 125
torek Avatar answered Sep 22 '22 12:09

torek