What to do when you commit to master by mistake in Git


Getting into trouble with Git

When you start a new implementation in git, you usually create a new branch, checkout to it, and start working on it. Then, when you're done, you commit and push to the new branch.

But sometimes, you forget to create a new branch. Here's how to deal with it.
This is a workaround for that.

The idea is to move the commit to the newly created branch (while keeping it) and revert the master branch to the previous commit.

The flow is as follows

Translated with (free version)


Implemented in master


Commit and push to master




Create a new branch and checkout



Return to master


Return to master

reset in master


Create a new branch

After you coomit to master, you can create a new branch


git checkout -b NewBranch
Switched to a new branch 'NewBranch'


Check NewBranch

A new branch called NewBranch has been created, and you can see that you are now on the master branch


git branch
* master


Checkout and return to master.


At this point, master and NewBranch should be in the exact same state.

From this state, let's go back to master with checkout.


git checkout master


Resetting while in the master branch

When you get back to master by checkout, use git reset to cancel the master commit.


git reset --hard HEAD~1


Now, NewBranch will have the latest commit, and master will have the previous commit.

LinkedIn にシェア



  • この記事を書いた人
  • 最新記事

藤沢瞭介(Ryosuke Hujisawa)



Copyright© , 2021 All Rights Reserved Powered by AFFINGER5.