AI Hints
Home›Git & GitHub Tutorial›Fixing Real Mistakes
Git & GitHub · Lesson 98 of 144

Committed to the Wrong Branch

Moving commits.

⏱ 2 min read▶ Video at 1:47:42🎓 Free
Watch this lesson in the Git & GitHub courseWatch on YouTube ↗Full Git & GitHub course

It happens to everyone. You meant to start a new branch, but you made two commits straight onto main. Don't worry. As long as you haven't pushed, it takes three commands to fix.

Committed to the Wrong Branch
From the video: Committed to the Wrong Branch
  • Two commits on main, by mistake
  • They belonged on a branch
  • Three commands to fix it

Moving the commits

Here are the two shop commits, sitting on main. First, git branch shop. That creates a branch pointing at our latest commit, so the work is safe there. Then git reset dash dash hard, head tilde two, moves main back two commits. Finally, switch to shop. The graph shows main back where it was, and both commits on the shop branch.

git
git log --oneline -n 3
931499e (HEAD -> main) Add coming soon note
1cca1e0 Start the shop page
f63a17a Link to about page
git branch shop
git reset --hard HEAD~2
HEAD is now at f63a17a Link to about page
git switch shop
Switched to branch 'shop'
git log --oneline --graph --all -n 3
* 931499e (HEAD -> shop) Add coming soon note
* 1cca1e0 Start the shop page
* f63a17a (main) Link to about page

Why this works

A branch is just a label on a commit. Creating the shop branch put a label on our work, so nothing could be lost. Then reset only moved the main label backwards. The commits never went anywhere. They just changed which label points to them.

git branch shoplabel the work
reset --hard HEAD~2move main back
git switch shopcarry on
Already pushed?ask your team first

Summary

Label the work with a new branch, reset main back, then switch to the new branch. Next, undoing a merge.

Key takeaways
  • git branch <new>
  • git reset --hard HEAD~N
  • git switch <new>
Next up: Undoing a Merge — revert -m 1