Git Rebase Guide
Rebasing is one of the most powerful—and most misunderstood—commands in Git. It is the art of Rewriting History.
1. What is a Rebase?
Rebasing is the process of moving or combining a sequence of commits to a new base commit. In simpler terms, it takes your feature branch and "re-plants" it at the very tip of the target branch (usually main).
2. Standard Rebase Workflow
When your feature branch has fallen behind main, follow these steps to catch up:
- Update Local Main:
git switch main->git pull - Start Rebase:
git switch my-feature->git rebase main - Handle Conflicts (If they occur):
- Edit the files to fix conflicts.
git add <file>git rebase --continue(Don't commit!)
- Final Result: Your feature is now on top of the latest project code.
3. Interactive Rebase (-i)
The most common professional use of rebase is to clean up messy local history before opening a Pull Request.
# Clean up the last 3 commits
git rebase -i HEAD~3Git will open a text editor with a list of your commits and available commands:
| Command | Action | Best For... |
|---|---|---|
pick | Use the commit as-is. | Default. |
reword | Use the commit but edit the message. | Fixing typos in messages. |
squash | Combine this commit into the previous one. | Merging small "fix-it" commits. |
fixup | Like squash, but discards the message. | Silently combining minor tweaks. |
drop | Remove the commit entirely. | Deleting accidental or buggy work. |
4. Rebase vs. Merge
| Feature | Merging | Rebasing |
|---|---|---|
| Philosophy | Preserve History. Shows exactly when work was combined. | Cleaner History. Linear log as if work happened in a straight line. |
| Commit Log | Messy (many merge commits). | Professional and readable. |
| Risk Level | Low. | High (rewrites history). |
[!CAUTION] The Golden Rule of Rebasing Never rebase a branch that has been pushed to a shared repository. Rebasing rewrites history by creating new commit IDs. If your teammates have already pulled the "old" version, rebasing will break their history. Only rebase your private, local branches.