0
0
Gitdevops~7 mins

Rebase vs merge mental model in Git - CLI Comparison

Choose your learning style9 modes available
Introduction
When working with Git, you often need to combine changes from different branches. Rebase and merge are two ways to do this, but they work differently. Understanding when to use each helps keep your project history clean and easy to follow.
When you want to update your feature branch with the latest changes from the main branch before finishing your work
When you want to combine changes from two branches but keep a clear history of how the work was done
When you want to avoid creating extra merge commits to keep the project history linear
When you want to preserve the exact history of how branches were combined, including merge points
When you want to prepare your branch for a clean integration into the main branch
Commands
Switch to your feature branch where you want to integrate changes from the main branch.
Terminal
git checkout feature-branch
Expected OutputExpected
Switched to branch 'feature-branch'
Rebase your feature branch on top of the latest main branch commits. This moves your changes to the tip of main, creating a linear history.
Terminal
git rebase main
Expected OutputExpected
First, rewinding head to replay your work on top of it... Applying: Add new feature
Switch back to the main branch to prepare for merging your feature branch.
Terminal
git checkout main
Expected OutputExpected
Switched to branch 'main'
Merge the feature branch into main. This creates a merge commit that shows the branches were combined.
Terminal
git merge feature-branch
Expected OutputExpected
Updating 1a2b3c4..5d6e7f8 Fast-forward file.txt | 2 ++ 1 file changed, 2 insertions(+)
View the commit history graph to see the difference between rebased and merged commits.
Terminal
git log --oneline --graph --all
Expected OutputExpected
* 5d6e7f8 (HEAD -> main) Add new feature * 1a2b3c4 Previous commit on main
Key Concept

If you remember nothing else, remember: rebase rewrites history to create a straight line of commits, while merge preserves the branch history with a merge commit.

Common Mistakes
Using rebase on a branch that others are also using
Rebasing rewrites history, which can confuse others and cause conflicts when they try to update their branches.
Use rebase only on local or private branches before sharing, and use merge for shared branches.
Merging without updating the feature branch first
This can create unnecessary conflicts or merge commits that could have been avoided.
Update your feature branch with rebase or merge from main before merging it back.
Summary
Use 'git rebase main' on your feature branch to apply your changes on top of the latest main branch commits, creating a linear history.
Use 'git merge feature-branch' on main to combine branches and preserve the full branch history with a merge commit.
Rebase rewrites commit history and should be used carefully, especially on shared branches.