Fix a branch you made from the wrong place with git rebase --onto

calendar_today timer Reading time ~1 minute

You accidentally branched off from the wrong branch. How do you fix the source?

Say you meant to branch off of main, but you accidentally branched off from task-1 instead. So now task-2, your new branch, has the wrong base.

git rebase --onto can be pretty handy in these situations.

You use git rebase --onto and give it three branches:

  1. main — the branch you wanted from the beginning
  2. task-1 — the wrong branch you used
  3. task-2 — the branch you want to fix the base of
git rebase --onto main task-1 task-2

Git replays your task-2 commits on top of main. That way task-2 continues to be your branch, but it has the right base.

The one rule with this command is that you always want to name the three branches to avoid dropping commits.

Want the full walkthrough with diagrams? I covered it here: Fixing the branch source with git rebase

Follow along for more git tips like this!

animated jess' signature

Related Articles