git rebase — Replaying Commits on a New Base
The git rebase command takes commits from one branch and replays them on top of another. It creates a linear history without merge commits.
Rebase vs Merge
Both integrate changes from one branch into another, but they work differently:
Merge: Rebase:
A — B — C — M (main) A — B — C — D' — E' (main)
\ / (linear history)
D — E (feature)
- Merge keeps all original commits and adds a merge commit
- Rebase replays your commits on top, creating new commits with the same changes
How It Works
Before rebase:
A — B — C (main)
\
D — E (feature)
After git rebase main (from feature):
A — B — C (main)
\
D' — E' (feature)
Commits D' and E' have the same changes as D and E, but they are new commits with new SHAs — they've been "replayed" on top of C.
Basic Usage
git checkout feature # Switch to the branch you want to rebase
git rebase main # Replay feature's commits on top of main
The Golden Rule
Never rebase commits that have been pushed to a shared branch. Rebase rewrites commit history (creates new SHAs). If others have based work on the original commits, rewriting them causes confusion and conflicts.
Safe to rebase:
- Your local feature branch before pushing
- Your feature branch that only you work on
Never rebase:
mainordevelopor any shared branch- Commits that others have already pulled
Try it!
Practice rebasing a feature branch onto main:
- Create an initial commit:
echo "base" > file.txt && git add file.txt && git commit -m "Initial commit"
- Create and switch to a feature branch:
git checkout -b feature
- Add a commit on feature:
echo "feature work" > feature.txt && git add feature.txt && git commit -m "Add feature"
- Switch back to main and add a commit:
git checkout mainecho "main update" >> file.txt && git add file.txt && git commit -m "Update main"
- Switch to feature and rebase onto main:
git checkout featuregit rebase main
- Check the log:
git log --oneline— your feature commit now sits on top of main's latest commit - Verify main's changes are included:
cat file.txt— shows "base" and "main update"
Handling Conflicts
If Git can't replay a commit cleanly, it pauses the rebase:
- Edit the conflicted files to resolve the conflicts
- Stage resolved files:
git add <file> - Continue the rebase:
git rebase --continue
To abort and go back to the state before the rebase: git rebase --abort
Key Points
- Rebase replays commits on a new base, creating a clean linear history
- It creates new commits (new SHAs) — the original commits are replaced
- Never rebase shared/public branches — only rebase your own local work
- Use
git rebase --abortto safely cancel a rebase in progress