Martin Kersten Martin Kersten - 3 months ago 14
Git Question

Git: Create new Branch after Commit before Pushing

I would like to know if and how I can create a new branch when I had already committed but not pushed.

Scenario:


  1. Switch to Master

  2. Change something

  3. Commit changes

  4. Create new Branch instead of Push



Basically I was told that this is not possible and that one has to push before creating a new branch. Since I did two days of work (like 10+ commits) and came to the conclusion that I would rather create a new branch instead of pushing these changes to master (I want to do additional testing prior since the changes became more bigger than anticipated).

Would I need to save all mal files, recheckout the master version I started with, create a new branch from it and restore my changes and recommit or can I just create a new branch which I originally thought (so I did not care at first)?

Answer

Basically I was told that this is not possible and that one has to push before creating a new branch.

That is absolutely not the case. You can create a new branch whenever you want. For example, after you had committed your changes, you could run:

git checkout -b newbranch

And that would create a new branch named newbranch based on the current commit. If you want to revert the master branch as part of this operation (that is, you want your changes only on the new branch, not on the master branch) you could do this:

# create a new branch, but don't switch to it
git branch newbranch

# Reset current (master) branch by discarding the most recent
# commit.
git reset --hard HEAD^

# Switch to new branch
git checkout newbranch

And now you can push your new branch to the remote server.

Comments