In Git, rebase
is a powerful command that allows you to rewrite commit history by moving or combining commits. It’s often used to clean up a feature branch before merging, or to incorporate the latest changes from a main branch without creating a messy commit tree.
In this guide, you’ll learn what git rebase
does, when to use it, and how to perform a rebase safely.
🧠 What Is Git Rebase?
git rebase
moves or “re-applies” commits from one branch onto another base commit. Unlike merge
, which creates a new merge commit, rebase
replays your changes on top of another branch, resulting in a linear history.
🔄 Rebase vs. Merge (Quick Comparison)
Feature | git merge | git rebase |
---|---|---|
Commit history | Keeps all commits, creates a merge commit | Linearizes history (no merge commit) |
Clarity | Shows full branch structure | Cleaner, straight-line history |
Use case | Collaborative workflows | Clean, private or local workflows |
✅ How to Use Git Rebase
Example Scenario
You have a feature
branch and want to bring in the latest commits from main
.
git checkout feature
git rebase main
This does the following:
- Rewinds your
feature
branch to the base ofmain
- Applies your feature commits on top of
main
🔁 Rebase Workflow: Step-by-Step
- Switch to the branch you want to rebase:
git checkout feature
- Run the rebase command:
git rebase main
- Resolve conflicts (if any): Git will pause and prompt you to resolve each conflict manually. After fixing, run:
git add <resolved-file> git rebase --continue
- Repeat until done.
✏️ Interactive Rebase (To Edit Commits)
git rebase -i HEAD~n
This opens an editor where you can:
pick
commits to keepsquash
commits to combinereword
commit messagesdrop
commits you no longer need
Perfect for cleaning up your commit history before pushing.
⚠️ Rebase Tips and Best Practices
- Never rebase public/shared branches. It rewrites history, which can confuse collaborators.
- Always pull with rebase to avoid unnecessary merge commits:
git pull --rebase
- Use
--onto
for advanced rebasing:git rebase --onto new-base old-base feature
📝 Summary
Task | Command |
---|---|
Rebase feature onto main | git checkout feature → git rebase main |
Resolve conflict | Fix → git add . → git rebase --continue |
Abort rebase | git rebase --abort |
Interactive rebase | git rebase -i HEAD~n |
Pull with rebase | git pull --rebase |
🎯 Use Cases for Git Rebase
- Clean up messy commit history
- Reapply changes on top of latest
main
- Prepare a feature branch for merge (with
--squash
) - Remove or edit old commits interactively
By mastering git rebase
, you gain the ability to shape your commit history exactly how you want it—clean, logical, and easy to read.