Git Rebase for the Terrified
Git Rebase for the Terrified
Let’s talk about git rebase. If you’ve been using Git for a while, you’ve probably heard whispers about it—usually followed by horror stories about destroyed repos and lost work. But rebase isn’t dangerous; it’s just powerful. Let me show you how to use it safely.
What Rebase Actually Does
Think of rebase as “replaying” commits on top of a different starting point:
# Before rebase
main: A---B---C
\
feature: D---E
# After rebase
main: A---B---C
\
feature: D'---E'
Your feature branch commits (D, E) get “replayed” on top of the latest main commit (C). The original commits don’t change—you get new commits (D’, E’) with the same changes but different parent commits.
The Golden Rule
Never rebase commits that have been pushed to a shared branch.
That’s it. Follow this rule and you’ll never cause problems for your team. Rebase is for cleaning up your local work before sharing it.
Common Use Cases
1. Update Your Feature Branch
# Instead of merge commits
git checkout feature
git merge main # Creates ugly merge commit
# Use rebase for a linear history
git checkout feature
git rebase main # Replays your commits on latest main
2. Clean Up WIP Commits
# Your messy history
git log --oneline
a1b2c3d wip
d4e5f6g fix typo
g7h8i9j actually implement feature
j0k1l2m oops, forgot tests
# Interactive rebase to clean it up
git rebase -i HEAD~4
In the interactive editor:
pick j0k1l2m implement feature
fixup d4e5f6g fix typo
fixup a1b2c3d wip
pick j0k1l2m add tests
Now you have two clean commits instead of four messy ones.
Interactive Rebase Commands
pick: Keep this commit as-isreword: Keep changes, edit commit messageedit: Pause here to amend the commitsquash: Combine with previous commit, keep both messagesfixup: Combine with previous commit, discard this messagedrop: Remove this commit entirely
When Things Go Wrong
If you panic during a rebase:
# Abort and go back to where you started
git rebase --abort
# Or use the reflog to recover anything
git reflog # Find the commit before you started rebasing
git reset --hard HEAD@{5} # Go back to that state
The reflog is your safety net. Git keeps your commits around for ~30 days even if they’re not on any branch.
My Workflow
# Work on a feature
git checkout -b feature/new-thing
# Make messy commits while working
git commit -m "wip"
git commit -m "more wip"
git commit -m "tests"
# Before creating PR, clean up history
git fetch origin
git rebase -i origin/main
# Squash WIP commits, write good messages
# Force push to my feature branch (safe because it's mine)
git push -f origin feature/new-thing
Why Bother?
Clean history makes:
- Debugging easier:
git bisectworks better with atomic commits - Code review better: Each commit tells a story
- Reverts safer: Can revert whole features cleanly
Rebase is a tool for crafting history. Use it to tell a clear story about how your code evolved.
Don’t be scared. Be deliberate.