create branch with N-last commits

Create a new branch, then reset the head to origin/master

git branch new_branch
git reset --hard origin/master

Attention: This last command will discard anything which you have in your working copy and not yet committed. Use git stash before if there is anything you want to preserve.

Then checkout your new branch

git checkout new_branch

knittl's answer works, but there are other ways to do this.

I'm assuming you're on the master when you first cloned this repository the master branch will match the master branch on the repository you've cloned from. This is origin/master. Since your question starts with a clone this is a fair assumption.

So, after you've made your commits on the master branch, you are now ahead of the origin/master branch.

The first thing you do is create a new branch

git branch new_branch

Note: this command just creates a new branch but doesn't switch branches. So master and new_branch now point to the same commit, but you are still on the master branch.

Next thing to do is to set the current branch (which is master) to the state it was before you added commits. This is the same state as origin/master so you issue this command

git reset --hard origin/master

This sets the current branch to the same state as origin/master. The --hard sets the index and the working tree to the initial state. There are other flags, but they don't do what you want here. (Attention: If you had uncommitted changes in your working tree, they are now thrown away. Use git stash in this case before the reset.)

So now you're on master which points the same state as origin/master, all you need to do is switch to the new branch:

git checkout new_branch

Yes, this is a bit longer (3 commands instead of 2), but you don't have to count how many commits you've got to go back, and this will work even if you've branched, merged, and rebased; and I get to explain other ways of doing things in Git.


Easy, check out your new branch, then move the old branch (let's assume master and 3 commits were made) back:

git checkout -b my_new_branch
git branch -f master HEAD~3

Tags:

Git