Full Byte Developer.

Move commits from main to a branch in three commands

Committed to main by accident? Move your work to a branch without counting commits or using reset --hard.

Published here · 1 source

Your work landed on main instead of a branch. Move it in three commands, without counting commits and without reset --hard.

Fetch so origin/main is current

Make sure you have the latest remote state. Uncommitted edits stay where they are.

bash
git fetch

See what moves

List the commits that only exist on your local main [1].

bash
git log --oneline origin/main..main

You should see each commit that will move to the new branch. If this prints nothing, your commits are already pushed. Skip the rest and use revert plus cherry-pick instead.

Create the new branch

Switch creates a branch at your current commit. Your commits and uncommitted edits come with you.

bash
git switch -c login

You should see "Switched to a new branch 'login'".

Point main back to the remote

Reset main to match what the remote has [1].

bash
git branch -f main origin/main

You should see no output. Run git log --oneline main to confirm main now ends at the remote's commit.

In a test repo: main went back to "base", the login branch kept "add login form" and "add login tests", and the uncommitted edit stayed put.

Your work is now on a branch. Main matches the remote.

Send this to the friend who just committed to main by accident and is about to hard reset.

Keep this guide

By Full Byte Developer

Filed under Dev tools

Questions about this guide

What if my commits are already pushed?

Do not rewrite main. Revert on main, then cherry-pick the original commits onto a new branch. Merging the old branch after a plain revert brings nothing back.

What happens to uncommitted edits?

They stay where they are. The switch command brings them along to the new branch.

Sources

  1. Git docs: git-branchraw.githubusercontent.com

Next in this stack