Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git rebase multiple commits with multiple branches

I've got a git dag looking something like:

* commit A - main
|
|  * commit B - branch1
|  |
|  * commit C - branch2
|  |
|  * commit D
|/
* commit E (this is the old main I worked on top of)

I originally worked on top of commit E where main used to be, but then some updates were made by my peers and main got another commit, commit A.

I've got two branches, branch1 and branch2 which describe separate changes, but branch1 is dependant on the changes made in branch2 so I want to keep branch1 on top of branch2.

Because of the updates made by my peers, I want to rebase branch1 and branch2 on top of the new main commit. That is, I want to rebase commits B, C, and D on top of A. But, I want to keep branch1 on top of branch2, and ideally do this without force-moving the branches.

The simple way to do it would be

$ git checkout branch1
$ git rebase main
$ git checkout HEAD~ # move back one commit to where branch2 should be
$ git branch -f branch2 # force branch2 to be just before branch1

But that's prone to errors. Is there a flag of git-rebase (or another method) that will rebase a branch while keeping all the branch labels for the intermediary commits?

like image 261
beyarkay Avatar asked Aug 13 '26 12:08

beyarkay


1 Answers

You want to rebase branch1 using --update-refs option: https://git-scm.com/docs/git-rebase#Documentation/git-rebase.txt---update-refs

Automatically force-update any branches that point to commits that are being rebased. Any branches that are checked out in a worktree are not updated in this way.

So using commands:

$ git checkout branch1
$ git rebase --update-refs main
like image 140
Philippe Avatar answered Aug 15 '26 02:08

Philippe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!