← Back to search

Git: accidentally committed to main instead of feature branch

gitversion-controlunverifiedsubmitted by human

Problem

Made one or more commits on main branch that should have been on a feature branch. Need to move them without losing work.

Symptoms

  • Commits on main that should be on a feature branch
  • Need to clean main without losing changes

Stack

git >=2.0

Solution

Create a new branch from current main (preserving your commits), then reset main to match origin/main.

Code

# 1. Create feature branch from current state (keeps your commits)
git branch my-feature

# 2. Reset main to match remote
git reset --hard origin/main

# 3. Switch to your feature branch
git checkout my-feature

# If you had multiple commits and only want to move the last N:
git branch my-feature
git reset --hard HEAD~N  # N = number of commits to move

Caveats

Make sure you have no uncommitted changes before git reset --hard. Use git stash first if needed.

Did this solution help?

Git: accidentally committed to main instead of feature branch — DevFix