Git Command Finder & Cheat Sheet · Tutorial

How to move commits made on main to a new branch

6 min readintermediateUpdated

You started working and committed twice before noticing you were on main instead of a feature branch. You will move the commits to a new branch and reset main, without losing anything.

What you need

Steps

  1. Count the commits to move

    Run git log --oneline -5 and count how many of the newest commits belong on the new branch. In this tutorial it is two.

  2. Create the branch where you are

    git branch feature/search creates a branch pointing at your latest commit, so the work is safe there before main changes.

  3. Move main back

    git reset --hard HEAD~2 moves main back two commits. The commits now exist only on the new branch. Make sure you have no uncommitted changes first.

    git branch feature/search
    git reset --hard HEAD~2
    git switch feature/search
  4. Carry on working

    Switch to the new branch and continue. git log --oneline there shows your two commits.

Try it yourself

Opens the Git Command Finder & Cheat Sheet with this tutorial's sample loaded.

Try it now

Common mistakes

You had already pushed main
Then others may have the commits. Don’t reset main; push the new branch and revert the commits on main with git revert.
Uncommitted changes disappear
reset --hard discards them. Stash them first with git stash push, and bring them back with git stash pop on the new branch.

Next steps

Go back to the Git Command Finder & Cheat Sheet, or keep going with one of these: