Take all my changes on the current branch and move them to a new branch in Git

GitBranch

Git Problem Overview


I started work on what I thought would be a minor bug fix on my master branch. However, it has spiraled out of control to the point where I wish I had created a separate branch to do the development in the first place.

So right now what I'd like to do is:

  1. Create a new branch called (say) "edge"
  2. Move all the changed / untracked files on master to edge (such that master is unchanged from when I started the bug fix)
  3. Finish my work on edge, merge back into master

How can I do this?

Git Solutions


Solution 1 - Git

If you haven't been committing anything yet, you're already in the right position.

  1. Create a new branch: git checkout -b edge
  2. Your files haven't changed. Just git add what needs to and commit as usual.
  3. When you're done committing on edge, switch back to master with git checkout and git merge edge.

Solution 2 - Git

To add to JB's answer, if you have already started to make a few commits on master for what ended up as being a "edge" effort, you could:

git stash
git checkout -b edge master
git branch -f master SHA1_before_your_commits
git stash apply

Solution 3 - Git

If you are trying to move the work from master to a branch that already exists, but is behind master, git won't let you switch to the other branch. In this case, do this:

git stash
git checkout oldBranch
git merge master
git checkout master
git stash apply
git checkout oldBranch

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTom LehmanView Question on Stackoverflow
Solution 1 - GitJB.View Answer on Stackoverflow
Solution 2 - GitVonCView Answer on Stackoverflow
Solution 3 - GitJesse PView Answer on Stackoverflow