Skip to content

Accidentally committed to wrong branch

Quick summary

You committed work to the wrong branch — the commit is on main but should be on a feature branch, and you need to relocate it safely.

Why this happens

  • You forgot to create or switch to a feature branch before starting work and committed directly to main

  • A previous git checkout left you on an unexpected branch and you did not verify with git branch before committing

  • An automated tool or IDE committed on your behalf to the currently checked-out branch without your awareness

Minimal example

✗ Broken code
git checkout main
git commit -m 'new feature'  # oops, should be on feature branch
git push origin main  # pushed to wrong branch!
✓ Fixed code
git branch feature/new  # create feature branch at current commit
git checkout main
git reset --hard HEAD~1  # remove commit from main
git checkout feature/new  # commit is now only on feature/new

Creating a branch at the current commit preserves the work, then resetting main back one commit removes it from main while keeping it on the new branch.

How to diagnose

  • Run git branch --show-current to confirm which branch you are on and git log --oneline -3 to see recent commits

  • Check git log --oneline main..HEAD or git log --oneline HEAD..main to understand the divergence from main

  • Use git reflog to find the exact commit hash you need to move if it is not the most recent one

How to fix

  • Create a new branch from the current commit with git branch feature/new, then reset main back with git checkout main && git reset --hard HEAD~1

  • Use git cherry-pick to copy the commit to the correct branch, then reset the wrong branch back to remove it

  • If already pushed, force-push the corrected branch with git push --force-with-lease after resetting main locally

How to prevent

  • Always check git branch --show-current before committing and use branch protection rules on main to prevent direct commits

  • Configure your IDE or shell prompt to display the current branch prominently to avoid committing to the wrong one

Related Resources

Related Glossary

Related Lessons

← Back to language