• Now all data be ready for publish, We had made our blog alive now. Haha.

  • These days CCP GFW blocked all the IPs from US and when I switch my IP in google Cloud, the disk data cannot be restore again. I have to restart my blog totally, Now the website is still building…

Move the most recent commit(s) to a new branch with Git- Stack Overflow

Python PingBook 2 months ago (10-26) 18 0


I’d like to move the last several commits I’ve committed to master to a new branch and take master back to before those commits were made. Unfortunately, my Git-fu is not strong enough yet, any help?

I.e. How can I go from this

master A – B – C – D – E

to this?

newbranch C – D – E
master A – B


Moving to an existing branch

If you want to move your commits to an existing branch, it will look like this:

git checkout existingbranch
git merge master # Bring the commits here
git checkout master
git reset –keep HEAD~3 # Move master back by 3 commits.
git checkout existingbranch

The –keep option preserves any uncommitted changes that you might have in unrelated files, or aborts if those changes would have to be overwritten — similarly to what git checkout does. If it aborts, git stash your changes and retry, or use –hard to lose the changes (even from files that didn’t change between the commits!)

Moving to a new branch

This method works by creating a new branch with the first command (git branch newbranch) but not switching to it. Then we roll back the current branch (master) and switch to the new branch to continue working.

git branch newbranch # Create a new branch, containing all current commits
git reset –keep HEAD~3 # Move master back by 3 commits (Make sure you know how many commits you need to go back)
git checkout newbranch # Go to the new branch that still has the desired commits
# Warning: after this it’s not safe to do a rebase in newbranch without extra care.

But do make sure how many commits to go back. Alternatively, instead of HEAD~3, you can simply provide the hash of the commit (or the reference like origin/master) you want to revert back to, e.g:

git reset –keep a1b2c3d4

WARNING: With Git version 2.0 and later, if you later git rebase the new branch upon the original (master) branch, you may need an explicit –no-fork-point option during the rebase to avoid losing the commits you moved from the master branch. Having branch.autosetuprebase always set makes this more likely. See John Mellor’s answer for details.

Copyright from PingBook Blog, If not specified, they are original. This site uses BY-NC-SAProtocol authenticated.
For reprinting, please indicate the link of the original text:Move the most recent commit(s) to a new branch with Git- Stack Overflow
LIKE (0)
We create, We sharing! Tag every value data your sharing
Submit comments
Cancel comments
emoji picture bold strikethrough center italic check in

Hi,you need to provide your name and email adress!

  • Name (Required)
  • Email (Required)
  • Website