Git Rebase二次操作如何避免合并提交,保持线性提交历史
Let's figure out why that unexpected merge commit popped up and how to fix it to get the linear history you're aiming for.
Why the Merge Commit Happened
First, a quick recap: when you did the first rebase, Git actually copied your CommitB1 and CommitB2 onto the end of Branch A's updated history (CommitA1 -> CommitA2). Those original CommitB1/B2 from before the first rebase are now hidden in Git's reflog, but if for some reason your Branch B ended up with a merge—maybe you accidentally ran git merge A instead of rebase, or had unresolvable conflicts that Git auto-handled with a merge—that's why you're seeing a merge commit tied to CommitInitialA on the second rebase.
Step-by-Step Fix to Get Linear History
Follow these steps carefully to rewrite Branch B's history into the clean linear sequence you want:
Make sure Branch A is up-to-date
First, switch to Branch A and ensure you have all the latest commits (CommitA3 included):git checkout A # If working with a remote, run git pull here; skip if it's purely localSwitch back to Branch B
git checkout BRun a standard rebase (or interactive rebase for more control)
To reapply all of Branch B's commits onto the latest state of Branch A:git rebase AIf you want to double-check which commits are being moved (to avoid surprises), use interactive rebase instead:
git rebase -i AIn the text editor that pops up, you'll see a list of Branch B's commits (CommitB1, CommitB2, CommitB3) marked with
pick. Just save and exit the editor—no changes needed here unless you want to edit/squash commits.Resolve conflicts (if any)
If Git hits conflicts between Branch B's commits and CommitA3, it will pause the rebase. Resolve the conflicts in your files, then stage the changes:git add .Then continue the rebase:
git rebase --continueRepeat this until the rebase completes.
Verify the Result
Once done, run git log --oneline to check the history. You should see the clean linear sequence you wanted:
<CommitInitialA hash> CommitInitialA <CommitA1 hash> CommitA1 <CommitA2 hash> CommitA2 <CommitA3 hash> CommitA3 <CommitB1 hash> CommitB1 <CommitB2 hash> CommitB2 <CommitB3 hash> CommitB3
Key Note
Remember: rebase rewrites Git history. If you've already pushed Branch B to a remote repository, you'll need to force push with git push --force-with-lease (safer than --force) to update the remote branch. Only do this if you're the only one working on Branch B, as it will overwrite the remote history.
内容的提问来源于stack exchange,提问作者Chubsdad

