Git rebase is a Git command used to move or reapply commits from one branch onto another base commit, creating a clean, linear commit history.
πΉ What Rebase Does (Conceptually)
Instead of merging branches with a merge commit, rebase rewrites commit history.
Before rebase
main: A ββ B ββ C
feature: βββ D ββ E
After rebase
main: A ββ B ββ C ββ D' ββ E'
(D and E are replayed on top of C)
πΉ Why Use Git Rebase?
β Keeps history linear and clean
β Avoids unnecessary merge commits
β Easier to read project history
β Useful before merging feature branches
β Basic Rebase Command
git checkout feature
git rebase main
πΉ Interactive Rebase (Most Powerful)
git rebase -i HEAD~3
Used to:
- Squash commits
- Reorder commits
- Edit commit messages
- Remove commits
β οΈ Important Warning (Interview Favorite)
β Never rebase public/shared branches
β Rebase only local or feature branches
Because rebase rewrites commit history.
π Rebase vs Merge (Quick Comparison)
| Rebase | Merge |
|---|---|
| Linear history | Preserves full history |
| Rewrites commits | Creates merge commit |
| Cleaner log | Shows branch structure |
| Risky on shared branches | Safe everywhere |
π― Short Interview Answer
Git rebase is used to move a branch’s commits onto another base commit, creating a linear and clean commit history. It rewrites history and should only be used on local or feature branches.
β One-line summary
Rebase rewrites history to make commits look like they were made sequentially.