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.
just-realized-i-had-to-branch-3-commits-ago

Basically you want to start from a situation like this:
moving-last-commits-before

and then obtaining this:

moving-last-commits-after

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 :)

Ciao,
Nando :)

Leave a Reply

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