Git Pills – Moving last n commits of a branch to a new branch

This time I want to share with you a simple trick I had to learn from the beginning, when branching was not an established habit for me.

It happens that you are working on a Git branch, and after some commits, you realize that your branch is taking a side road.

Basically you want to start from a situation like this:

and then obtaining this:


Creating a new branch and moving off last n commits is quite easy to do, fortunately; you have only to create a new branch at the point you want to diverge, and then reset the original branch back to the number of commits you desire; for example, let’s try to branch off master branch, moving out last 5 commits in a new feature1 branch:

Bare in mind that using –hard, you will lose all the uncommitted work on master branch; previous commits instead will be preserved.

But remember: it is safe to do this only if you don’t have already pushed commits to a remote; in that case, rewriting history is heavily discouraged: if you try, a hungry T-Rex will jump out from the shell, pretending to eat your head :)

Nando :)

Leave a Reply

Your email address will not be published. Required fields are marked *