Git logo

Git: Committed on master instead of forking a branch

Git Logo by Jason Long is licensed under the Creative Commons Attribution 3.0 Unported License.

Sometimes we start working on a feature but mistakenly commit on the master branch. We realize the mistake too late and would like to “move” this commit or commits to a new feature branch. In this post I explain the fastest way to do this, if the commits have not been pushed to upstream yet.

First, if you already pushed the commit to upstream, you should first git revert the commit and then read about git server-side hooks to prevent you to push directly on master again. I won’t explain this scenario in detail nor discuss direct pushes on master.

Next, let’s see how to solve our problem. The situation is not really complicated, especially if you keep in mind that branches in git are just pointers to commits. You can see this for example just typing from the repo’s root directory:

which will print the commit the master branch is pointing at. In a picture our situation is as follow:

The solution is:

1. Create a new branch pointing at master/HEAD
2. Move the master branch (pointer) back one commit

In git commands this becomes:

Note in the last command we need the ‘–hard’ option otherwise the changes in the bad commit will be left as unstaged/untracked in our working directory.

Categories: git