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.
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:
user@computer /home/Source/Project (master)
$ git branch feature1
$ git reset --hard HEAD~5
$ git checkout feature1
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 :)