Introduction
Rebasing is one of the most powerful — and sometimes misunderstood — features in Git. It allows you to rewrite commit history and maintain a cleaner, more linear project history.
In this post, we’ll walk through:
- What
git rebaseis - How to use it in common scenarios
- The difference between rebase and merge
- How to resolve conflicts during a rebase
What is Git Rebase?
Rebasing is the process of moving or combining a sequence of commits to a new base commit. Unlike merge, which creates a new commit that ties branches together, rebase re-applies your changes on top of another branch.
Basic Rebase Example
Let’s say you're working on a feature branch:
git checkout -b featureYou make a few commits. Meanwhile, main has moved forward. You want to update your feature branch with the latest changes from main:
git checkout featuregit rebase mainThis takes your feature branch commits and reapplies them on top of the latest commit from main.
Rebase vs Merge
| Command | Description |
|---|---|
git merge | Combines branches and creates a merge commit |
git rebase | Rewrites commit history and avoids merge commits |
Merge:
git checkout featuregit merge mainCreates a new commit that merges main into feature.
Rebase:
git checkout featuregit rebase mainNo merge commit — it rewrites the history of feature as if it were built directly on top of main.
Interactive Rebase
To clean up your commit history before merging:
git rebase -i HEAD~3This opens an editor showing your last 3 commits. You can choose to:
pick(keep as is)squash(combine with previous commit)reword(edit commit message)
Example:
pick a1b2c3 Add user modelsquash d4e5f6 Fix typo in user modelreword f6g7h8 Add validation to user modelAfter saving, Git will prompt you to edit the combined commit messages.
Resolving Conflicts
If there’s a conflict during rebase:
# Fix the conflict in your editorgit add .git rebase --continueTo abort the rebase:
git rebase --abortTo skip the problematic commit:
git rebase --skipRebasing a Feature Branch
A common workflow is to rebase your feature branch before merging:
git checkout featuregit rebase main# Fix any conflicts, then:git checkout maingit merge featureThis gives you a clean, linear commit history without merge commits.
Don't Rebase Shared History
Never rebase commits that have already been pushed to a shared branch (e.g., main, develop) unless everyone agrees. Rebasing rewrites history, which can cause issues for collaborators.
If you must rebase a pushed branch, use force-push with caution:
git push --force-with-leaseConclusion
Rebasing is a powerful tool that helps you create clean and readable Git histories. Use it to:
- Update branches
- Clean up commits
- Avoid messy merge commits
But remember: with great power comes great responsibility. Only rebase local or personal branches unless you coordinate with your team.
Happy rebasing! 🔧