Sub topic 6
Moving a Branch off a Feature Branch and onto main
This chapter covers one of the most common uses of git rebase --onto: you started a branch from another feature branch, and now you want it to depend on main instead. It assumes you can commit, branch, switch, and read git log. It also assumes you know a branch is a movable pointer to a commit. A plain git rebase is helpful background but not required, because the chapter explains what it does.
The situation
Suppose you needed a helper that another developer was still writing on a branch called next. You started your own branch, topic, from the tip of next and added two commits. Meanwhile main kept moving.
Now next is stalled, or was abandoned, or you simply realize topic doesn't need it. You want topic to contain only your two commits, sitting on top of the current main.
o---o---o---o---o main
\
o---o---o next
\
o---o topicA plain git rebase main gets this wrong, as the next section shows.
Why a plain rebase is not enough
Running git rebase main while on topic means "replay every commit reachable from topic but not from main, and put the copies on top of main."
Here the commits reachable from topic and not from main are the three commits on next plus your two commits. Git replays all five. You get a topic that carries a second copy of next's work, and next itself still has the originals. If next is later merged, you will see duplicated changes or conflicts.
A plain rebase uses one argument for two jobs. It is both the new base and the boundary that says which commits to replay. --onto splits those jobs apart.
The three arguments
git rebase --onto <newbase> <upstream> <branch>| Argument | Job | In this example |
|---|---|---|
| `<newbase>` | Where the copied commits are placed | `main` |
| `<upstream>` | Boundary of the range. Commits reachable from it are excluded | `next` |
| `<branch>` | The branch to move. Git switches to it first | `topic` |
Git selects the commits in upstream..branch, which means "reachable from branch, not reachable from upstream." It then copies them, in order, onto newbase, and finally points branch at the last copy.
Read the command aloud as: "Take the commits of topic that are not in next, and put them on main."
For our example:
git rebase --onto main next topicHere is the shape of the history before and after.
Three things to notice:
nextdoes not move. Its commits are untouched, and onlytopicis rewritten.T1 copyandT2 copyare new commits with new IDs. They have the same changes and messages, but different parents. The oldT1andT2are no longer reachable from any branch.N1andN2are not part oftopicanymore, because they were excluded bynextas the upstream.
Try it in a scratch repository
This script builds the exact history above, using separate files so no conflicts occur. You can paste it into a terminal.
git init -b main onto-demo
cd onto-demo
git config user.name "Demo"
git config user.email "[email protected]"
echo base > base.txt
git add base.txt
git commit -m "M1: base"
git switch -c next
echo n1 > next1.txt
git add next1.txt
git commit -m "N1: next work"
echo n2 > next2.txt
git add next2.txt
git commit -m "N2: more next work"
git switch -c topic
echo t1 > topic1.txt
git add topic1.txt
git commit -m "T1: my first change"
echo t2 > topic2.txt
git add topic2.txt
git commit -m "T2: my second change"
git switch main
echo m2 > main2.txt
git add main2.txt
git commit -m "M2: main moves on"
echo m3 > main3.txt
git add main3.txt
git commit -m "M3: main moves on again"Now compare the plain rebase with --onto. First, preview what each would replay:
# What a plain "git rebase main" on topic would replay:
git log --oneline main..topic
# What "--onto main next topic" will replay:
git log --oneline next..topicThe first command lists four commits (T2, T1, N2, N1). The second lists two (T2, T1). That second list is the exact set of commits --onto will copy, so read it before you run the rebase.
Then run the rebase and inspect the result:
git rebase --onto main next topic
git log --oneline --graph --decorate main next topicYou should see topic as a straight line: M1, M2, M3, then T1 and T2. next still branches off at M1 with N1 and N2.
Check the result
Counting commits is a good first check, but you can verify more directly.
# Only your commits should appear here (2 in the demo):
git log --oneline main..topic
# Nothing from next should be in topic:
git log --oneline topic..next
# Compare the old and new versions of your commits, pair by pair:
git range-diff next..ORIG_HEAD main..topicThe second command shows N2 and N1, which is correct because next has commits that topic no longer has.
git range-diff lines up each old commit with its rewritten copy. It shows = when the commit is identical in content and a diff when it changed, for example because you resolved a conflict. Git sets ORIG_HEAD to the old tip of topic when the rebase starts, which is why it works as the "before" side. Later commands, such as a reset or another rebase, can overwrite ORIG_HEAD, so run this check right away.
Details that matter
The branch argument is optional
If you are already on topic, you can leave it out:
git switch topic
git rebase --onto main nextWhen you name a branch, Git runs git switch on it first. If the branch isn't the one you are on, the rebase leaves you on that branch afterwards.
The upstream can be any commit
next is a convenient label, but the upstream can be a commit hash, a remote-tracking branch such as origin/next, or a relative name such as topic~2. Use a hash when the branch you started from has since moved or been deleted. If next has received new commits since you branched, next as the upstream would be wrong, because it would exclude commits that were never in your history. In that case, find the real fork point and use that hash:
git merge-base next topicPass the printed hash as the upstream.
Merge commits are flattened
By default a rebase drops merge commits from the range and replays only the non-merge commits, in a linear order. If your branch contains merges you want to keep, add --rebase-merges. This chapter assumes a linear branch.
Commits already in the new base are skipped
If a commit in the range has the same change as one already in newbase (matched by patch ID), Git omits it. This helps when part of your work was already merged by cherry-pick. It also explains why a rebase sometimes replays fewer commits than git log upstream..branch shows.
Your working tree must be clean
Git refuses to start a rebase with uncommitted changes to tracked files. Commit them, stash them, or pass --autostash.
When a copied commit conflicts
Each commit is applied one at a time, and any of them can conflict with something on main. When that happens, Git stops and leaves the branch in the middle of the rebase. The normal loop is:
git status # shows the conflicted files
# edit the files to resolve the conflict markers
git add path/to/file
git rebase --continueTo give up and restore topic exactly as it was, run git rebase --abort. Later chapters cover conflicts and recovery in more detail.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Using `git rebase main` and expecting `next`'s commits to stay behind | All of `next`'s commits are copied into `topic` | Use `--onto main next topic` |
| Swapping the new base and the upstream (`--onto next main topic`) | Wrong range, wrong destination | Say it aloud: onto *new base*, excluding *upstream*, move *branch* |
| Using a moved `next` as the upstream | Commits that were never yours are excluded, or yours are missed | Use `git merge-base next topic` as the upstream |
| Skipping the preview | A wrong range is discovered only after history is rewritten | Run `git log --oneline <upstream>..<branch>` first |
| Rebasing a branch others have pulled | Collaborators hold the old commits and get duplicates | Coordinate first, or avoid rewriting shared history |
If it goes wrong
A finished rebase can be undone. Right after the rebase, ORIG_HEAD points at the old tip:
git reset --hard ORIG_HEADIf you have already run other commands, look for the old tip in the reflog and reset to it. The topic@{1} form means "where topic pointed one change ago."
git reflog
git reset --hard topic@{1}If topic was already pushed, the rewritten branch will need git push --force-with-lease origin topic. That has its own risks and is covered in a later chapter.
Summary of the procedure
- Make sure the working tree is clean.
- Identify the branch you started from (the upstream) and the branch you want as the new base.
- Preview with
git log --oneline <upstream>..<branch>. Confirm that only your commits are listed. - Run
git rebase --onto <newbase> <upstream> <branch>. - Resolve any conflicts with
git addandgit rebase --continue, or usegit rebase --abort. - Verify with
git log --oneline --graph --decorateandgit range-diff.
Exercise
You created branch report from the tip of branch parser, then added two commits to report. parser has three commits that are not on main. You want report to hold only its own two commits on top of main. Which command previews the commits that will be replayed, which command performs the move, and how many commits should the preview list?
Show answer
Preview with git log --oneline parser..report, which should list exactly 2 commits (the two on report). Move with git rebase --onto main parser report. If the preview shows more than 2 commits, the upstream is wrong (for example, parser has moved since you branched), so find the real fork point with git merge-base parser report and use that hash as the upstream.
Exercise
After running git rebase --onto main next topic, you realize you used the wrong upstream. You have not run any other Git commands. How do you restore topic to its state before the rebase?
Show answer
Run git reset --hard ORIG_HEAD while on topic. Git set ORIG_HEAD to the old tip of topic when the rebase started. If other commands have overwritten it, use git reflog to find the old tip and reset to it, for example with git reset --hard topic@{1}.