June 7, 2022

How to fix an accidental commit to main or master branch?

Every now and then I forget to actually checkout to a new branch when I start to work on a new task and then I find myself accidently commiting my work to the main/master branch and I have to google on how to bring the changes to a new branch and remove them from the main/master branch.

As long as the commits are not pushed to a remote repository - hopefully your main/master branch is protected from direct commits - it’s very easy to fix:

First of create a new branch with:

git branch my-new-branch

All the commits that you accidently commited to the main branch will now be available on this new branch.

You can then remove the accidental commits from main with:

git reset --hard origin/main

The changes are now removed from you local main branch but exists on the new branch that you created earlier, which you can now checkout to with:

git checkout my-new-branch