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
- The Git Command Finder
- A terminal in your repository
Steps
Count the commits to move
Run
git log --oneline -5and count how many of the newest commits belong on the new branch. In this tutorial it is two.Create the branch where you are
git branch feature/searchcreates a branch pointing at your latest commit, so the work is safe there before main changes.Move main back
git reset --hard HEAD~2moves 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/searchCarry on working
Switch to the new branch and continue.
git log --onelinethere shows your two commits.
Try it yourself
Opens the Git Command Finder & Cheat Sheet with this tutorial's sample loaded.
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 --harddiscards them. Stash them first withgit stash push, and bring them back withgit stash popon the new branch.
Next steps
Go back to the Git Command Finder & Cheat Sheet, or keep going with one of these: