2

I have started making some changes recently to my master branch to add featureX. I have created 1 new file and edited 6 others. I have not committed any of the changes. For the time being, I would like to work on featureX on a separate branch and leave the master untouched until I am sure featureX works correctly.

I know I should have started a new branch before I started making these changes for featureX, but is there anyway to get the uncommitted changes I've made to the master branch into a featureX branch and restore the master to its pre featureX state?

FunLovinCoder
  • 7,597
  • 11
  • 46
  • 57
  • 2
    You can actually switch branches and commit those changes to that branch, then go back to master. Otherwise, you can do `git stash`. – wkl Jul 11 '12 at 15:36

2 Answers2

4

Creating a new branch (git checkout -b your_new_feature) should do the job - otherwise, you could try this:

git stash
git checkout -b your_new_feature
git stash apply
girasquid
  • 15,121
  • 2
  • 48
  • 58
2

What you need is to stash away the changes, then apply it somewhere else:

git stash
git checkout -b other_branch
git stash apply

Read more on git stash here.


As I just learned (and tried), you can actually just checkout to your branch and git will remember what files were changed. So

git checkout -b other_branch

should be enough.


A note: It is important to also learn git stash. In this case, there is no problem. However, if the other_branch already exists, it may have its own changes and therefore there could be merge conflicts. In that case simply writing

git checkout other_branch

may fail with a message like this:

error: You have local changes to 'whatever'; cannot switch branches.

In such a case, you should use the method above and after git stash apply, resolve the possible conflicts.

Shahbaz
  • 46,337
  • 19
  • 116
  • 182