Mastering Git Rebase: A Practical Guide
Mastering Git Rebase: A Practical Guide
Git rebase is one of the most powerful — and most feared — tools in a developer's toolkit. Let's demystify it.
Rebase vs Merge
Both integrate changes from one branch into another, but they do it differently:
Merge creates a new "merge commit" that ties two branches together:
bash
git checkout main
git merge feature-branch
# Creates: A - B - C - M (merge commit)
# \ /
# D - ERebase replays your commits on top of the target branch:
bash
git checkout feature-branch
git rebase main
# Creates: A - B - C - D' - E'
# Clean, linear historyInteractive Rebase
This is where rebase really shines. Use git rebase -i HEAD~3 to modify your last 3 commits:
pick abc1234 Add user model
pick def5678 Fix typo in user model
pick ghi9012 Add user validation
# You can:
# pick - keep the commit as-is
# reword - change the commit message
# squash - combine with previous commit
# drop - remove the commit entirely
The Golden Rule
Never rebase commits that have been pushed to a shared branch.
Rebasing rewrites commit history. If others have based work on the original commits, you'll create conflicts and confusion.
Recovering from Mistakes
Made a mistake during rebase? Don't panic:
bash
# See the history of where HEAD has been
git reflog
# Reset to before the rebase
git reset --hard HEAD@{5}The reflog is your safety net. Git keeps a record of every change to HEAD for at least 30 days.
My Workflow
- Work on a feature branch
- Before merging, rebase onto main:
git rebase main - Squash WIP commits:
git rebase -i main - Push and create a PR with clean history
Explore by topic