31

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?

larryq
  • 15,713
  • 38
  • 121
  • 190
  • 1
    [**Dude.**](https://www.google.com/search?q=Forgot+to+branch+in+git%2C+need+to+move+changes+from+master). This question appears to be off-topic because googling the title produces excellent answers. – jthill Oct 26 '13 at 22:54
  • 13
    @jthill I found this question through a google search. Am I stuck in an infinite loop? – phoog Feb 06 '19 at 15:06

3 Answers3

46

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
torek
  • 448,244
  • 59
  • 642
  • 775
5
git branch -M master my-branch

With a -m or -M option, <oldbranch> will be renamed to <newbranch>. If <oldbranch> had a corresponding reflog, it is renamed to match <newbranch>, and a reflog entry is created to remember the branch renaming. If <newbranch> exists, -M must be used to force the rename to happen.

Source

and then

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

or

git branch master my-branch  (or another ref)
Thomas Weller
  • 55,411
  • 20
  • 125
  • 222
ensc
  • 6,704
  • 14
  • 22
  • That's a good way to change stuff that was *committed* to be on the new branch `my-branch`. – torek Oct 26 '13 at 22:24
3
git stash
git stash branch <branchname>
alko
  • 46,136
  • 12
  • 94
  • 102
  • That will work, but `git checkout -b ` is simpler (and a bit faster, it does not have to undo changes and then re-apply them). – torek Oct 26 '13 at 22:19