Git Tip: Branch your previous commit

August 21, 2012

I just made a commit (6452234) to master, but realized that is should have been committed to a branch and I want master pointing at a previous commit (bb5331e).  How do I resolve this?

C:\code\project>git lg
* 6452234 - (HEAD, master) reformat test variables
* bb5331e - (origin/master) more unit tests

First, create the new branch where you would like your commit to live:

git checkout -b cool-feature

Now your master and the new branch are pointing to the same commit, like this:

C:\code\project>git lg
* 6452234 - (HEAD, master, cool-feature) reformat test variables
* bb5331e - (origin/master) more unit tests

Go back to the master branch.

git checkout master

Now, reset your master branch to point the revision that you want to go back to:

git reset --hard bb5331e

Master is now pointing to the old revision and the new revision is on the branch only.  Checking the log, we can confirm this:

C:\code\project>git lg
* bb5331e - (HEAD, master, origin/master) more unit tests

To confirm that the commit has been moved to your branch, just checkout the branch and run the log:

C:\code\project>git checkout cool-feature
Switched to a new branch 'cool-feature'
C:\code\project>git lg
* 6452234 - (HEAD, cool-feature) reformat test variables
* bb5331e - (master, origin/master) more unit tests

Special thanks to Mark's great blog entry on not using Git pull. Also if you want to know how I got my Git logs to show up using 'git lg', check out my previous entry on git alias.

Share this:


comments powered by Disqus