Adventures in Git: Move Commits from Master to New Branch

Annika Backstrom
in Adventures in Git, on 1 December 2012. It is tagged #Computers and #git.

The other night, I sat down with Git to solve what turned out to be a very simple problem: what if you've started making commits to your master branch, but want to move your work into a feature branch? After staring at git log for a few minutes, I had a forehead-slapping moment. Here's one way to move recent commits into a branch:

Start with a clean master, based off origin/master:

{ "hash": "a" }, { "hash": "b" }, { "hash": "c" }

Make a few commits of your own:

{ "hash": "a" }, { "hash": "b" }, { "hash": "c" }, { "hash": "d" }, { "hash": "e" }, { "hash": "f" }

Now, let's move these commits to a branch. Simply create a new branch at the current commit, then reset master back to the state of origin/master.

(master)$ git branch my-feature
(master)$ git reset --hard origin/master
{ "hash": "a" }, { "hash": "b" }, { "hash": "c" }, { "hash": "d", "branch": "feature" }, { "hash": "e", "branch": "feature" }, { "hash": "f", "branch": "feature" }

That's all. No git rebase, no git cherry-pick, just make your branch and reset master.