Rebasing in Git is a powerful tool that lets you rewrite history to create a cleaner, more linear project timeline. While powerful, it must be used carefully—especially in collaborative environments.
In this post, you’ll learn:
- What rebasing is
- When to use it
- How to do it (with commands)
- Common rebase scenarios
🔄 What Is Git Rebase?
The git rebase command moves or reapplies your commits on top of another branch. It’s often used to:
- Sync your branch with the latest changes from
mainormaster - Clean up commit history before merging
- Avoid merge commits in feature branches
🆚 Rebase vs Merge: What’s the Difference?
| Feature | git merge | git rebase |
|---|---|---|
| History | Creates a merge commit | Rewrites history with new commits |
| Commit Log | Shows branching paths | Appears as a straight line |
| Use Case | Preserve history, team merges | Clean history, personal feature work |
✅ Basic Rebase Workflow
Scenario: You’re working on a feature branch and want to rebase it onto the latest main.
🔧 Step-by-Step:
- Switch to your feature branch:
git checkout feature - Rebase onto
main:git rebase mainThis will move yourfeaturebranch commits to the tip ofmain. - (If conflicts occur) Git will pause and allow you to fix them. After fixing:
git add . git rebase --continue - Repeat until rebase is complete.
🔄 Keeping Your Branch Updated
If main has new commits and you want your feature branch to include them:
# From your feature branch
git fetch origin
git rebase origin/main
📤 Rebasing Before a Pull Request
Before opening a PR, rebase your branch to ensure a clean and up-to-date history:
git checkout feature
git fetch origin
git rebase origin/main
Then force push (since rebase rewrites history):
git push --force
⚠️ Only force push to branches you control. Never rebase shared/public branches unless everyone agrees.
🔁 Interactive Rebase
To edit commits, squash, or reorder them:
git rebase -i HEAD~N
Replace N with the number of recent commits you want to rebase.
You’ll see a list like:
pick 1a2b3c First commit
pick 4d5e6f Second commit
Change pick to:
squash– combine with the previous commitedit– amend this commitdrop– remove the commit
🧠 Summary of Key Commands
| Task | Command |
|---|---|
Rebase your branch onto main | git rebase main |
| Continue after resolving conflict | git rebase --continue |
| Abort a rebase | git rebase --abort |
| Interactive rebase (edit commits) | git rebase -i HEAD~N |
| Force push after rebase | git push --force |
🚨 Best Practices
- Never rebase public/shared branches—only rebase your own.
- Always resolve conflicts carefully during a rebase.
- Use
git logbefore and after rebasing to understand changes.
🔚 Conclusion
Rebasing is an essential Git skill that helps maintain a clean and linear commit history. Use it to keep your work current, prepare for pull requests, and refine your project timeline.