Question:How do I move my recent commits on master to a new branch, and reset master to before those commits were made? e.g. From this:
Moving to an existing branch
If you want to move your commits to an existing branch, it will look like this:
git stash. Once complete, you can retrieve the stashed uncommitted edits with
git stash pop
Moving to a new branch
WARNING: This method works because you are creating a new branch with the first command:
git branch newbranch. If you want to move commits to an existing branch you need to merge your changes into the existing branch before executing
git reset --hard HEAD~3(see Moving to an existing branch above). If you don’t merge your changes first, they will be lost.
Unless there are other circumstances involved, this can be easily done by branching and rolling back.
HEAD~3, simply provide the hash of the commit (or the reference like origin/master) you want to “revert back to” on the master (/current) branch, e.g:
Lastly, you may need to force push your latest changes to main repo:
git rebasethe new branch upon the original (
master) branch, you may need an explicit
--no-fork-pointoption during the rebase to avoid losing the carried-over commits. Having
branch.autosetuprebase alwaysset makes this more likely. See John Mellor’s answer for details.
If you have better answer, please add a comment about this, thank you!