Merge vs Rebase: When to Use Which Git Strategy for Clean History
This article explains the differences between Git’s merge and rebase commands, illustrates their effects on commit history with diagrams and code examples, and offers guidance on choosing the appropriate strategy based on team workflow, project complexity, and the need for linear or preserved history.
When collaborating on code, developers often need to combine changes from different branches. Git provides two primary ways to do this: merge and rebase . Understanding their behavior helps you maintain a clear project history.
Merge Branches
Merge creates a new commit that combines the histories of the source and target branches, preserving all previous commits. This results in a non‑linear history but retains a complete record of how changes were integrated.
The graph below shows how a merge commit appears in the main branch, often making the commit history look more complex.
<code>git checkout main
git pull origin main
git merge dev
# resolve conflicts if any
git commit -m "Merge dev into main"
git push origin main</code>Rebase Branches
Rebase rewrites the commits of the source branch so that they appear as if they were made directly on top of the target branch, resulting in a linear and clean history without a merge commit.
Because rebase changes commit hashes, you often need to force‑push the updated branch.
<code>git checkout dev
git pull origin dev
git rebase main
# resolve conflicts if any
git rebase --continue
git push origin dev --force</code>Squash Commits
During a rebase you can squash multiple commits into a single one, simplifying the history. For example, three commits A, B, C on a feature branch can be combined into a single commit F on the main branch.
<code>git rebase -i HEAD~3
# change 'pick' to 'squash' for the commits you want to combine
# edit the commit message, then save and exit
git push origin dev --force</code>Choosing a Method
The best approach depends on your workflow and project needs. Use merge when you want to preserve the complete history of all branches, which is helpful for team collaboration and auditability. Use rebase when you prefer a linear, tidy history, especially for solo work or when preparing a feature branch for integration.
macrozheng
Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.