Git - Move Recent Commits To A Branch

Today I will show you how to perform the following change to your git repository:


A
A
B
B
C
C
D
D
Master
Master
New Branch
New Branch

After

[Not supported by viewer]
A
A
B
B
C
C
D
D
Master
Master

Before

<h2><b>Before</b></h2>

You may need to do this if you created a new branch, but forgot to switch to it before subsequently making your commits to master instead.

Steps

Run the following commands:

# Create the new branch
git branch myNewBranch      

# Move master back by 3 commits
git reset --hard HEAD~3

# Switch to this new branch 
git checkout newbranch

If you had already pushed the changes to a remote server, then you will need use force to push these steps to the remote server (and apologize to all the other developers in your team).

git push --force origin

Extra Steps For Gitlab Users

If you are using Github, the previous command should have succeeded and your all done. In my case, because I am resetting master on a Gitlab server, this was rejected with the following message:

! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'git@gitlab.xxx.org:Page/package-xxx-xx.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

This was easy enough to fix. Master branches are marked as "protected" by default. Simply unprotect them before running your force push again and then re-protect the branch.

References

Author

Programster

Stuart is a software developer with a passion for Linux and open source projects.

comments powered by Disqus
We are a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for us to earn fees by linking to Amazon.com and affiliated sites. More info.