1

I am new to Git and learning to use it for my project. Currently, I'm wondering how to switch uncommitted work to a branch when I have accidentally been working in master. I am working on my own, but want to keep things organized anyway.

For example, I have made a series of commits and master is up to date. I then begin working on the master branch, but decide the work will be more involved than predicted, so I would prefer to be doing it in some other branch.

I can certainly commit the changes up till then to master and then start from there in a new branch, but I would rather have all the stuff I've been doing since my last commit in that new branch. What is the simple approach to doing this?

Is this a case where a git reset --soft would be needed? Or is there a simpler approach? Thanks.

teepee
  • 2,286
  • 2
  • 16
  • 29
  • 1
    Just start the new branch (e.g. `git co -b branchname`), it will come with all the commits and any uncommitted WIP you had on the branch you started from. – jonrsharpe May 25 '18 at 15:42
  • I thought it might be simple! Thank you for that help. – teepee May 25 '18 at 16:34
  • Possible duplicate of [Move existing, uncommitted work to a new branch in Git](https://stackoverflow.com/questions/1394797/move-existing-uncommitted-work-to-a-new-branch-in-git) – phd May 25 '18 at 21:21

1 Answers1

3

I see three cases :

  1. you want to continue on a new branch, created from the las commit on master :

    git checkout -b name-of-new-branch
    

    Then you can commit in the new branch

  2. you want to continue on an existing branch (that-branch), and the current WIP touches no file that is different in that-branch and in master (don't worry, git will complain if that's the case) :

    git checkout that-branch
    

    If the checkout works, you can commit

  3. some files are different in that-branch and in master (git complained when you tried 2. :

    git stash
    git checkout that-branch
    git stash apply
    

There may be conflicts that you have to then resolve. If you can't (merges can be hard), don't feel overwhelmed, and git reset HEAD --hard. The stash will still be here and you can go back to master and do step 1, before trying to merge in a conventional way.

You could also git stash pop, but I always stress that I'll lose work if it fails.

Boris
  • 1,033
  • 9
  • 19