Rewind master if you forgot to create new branch in Git

2012-04-21
My situation in Git was this: I'd continued to work in the master branch and made a few commits when I realized that I should do this new stuff in a separate branch and keep the master where it was several commits ago. Turns out this is very simple to do, but I thought that it was worth a blog post anyway.

The steps are quite simple. Assuming I’m in the master branch with a few commits I’d like to rewind but keep the code that I have in a new branch.

1. Create a new branch for the current code

git branch new-experiments

2. Determine how far back I’d like to rewind master

git log

When looking at the log, find the last commit I want to keep and make a note of its hash tag. It will be used in the next step.

3. Rewind/move master back to found commit

git reset --hard ab15cd26

4. Go back to where I was by checking out the newly created branch

git checkout new-experiments

5. Also, I got an error message when I tried to push these changes to a central repository (Github) for the master branch. So I needed to force the push with:

git push --force github master

That’s it!

2 Responses to “Rewind master if you forgot to create new branch in Git”

  1. Kim says:

    Thank you so much!!! That was exactly what I have been searching for. We were developing on the master branch and at some point we decided that we shouldn’t merge our code to the master, but rather to a development branch. I’ll try it out :)!

  2. BombeR says:

    This is a life-saver, thank you!
    From now on, I will use GIT in console only! 🙂
    EGIT = big no-no

Leave a Reply

Twitter: @mikeplate