Overview
Git rebase is an alternative to merging that rewrites commit history to create a cleaner, more linear project history. Instead of creating a merge commit, rebasing moves or combines a sequence of commits to a new base commit.
Steps
- Update your local main branch:
git checkout main
git pull
- Switch to your feature branch:
git checkout feature-branch
- Rebase your branch onto the latest main:
git rebase main
-
If there are conflicts, resolve them:
- Edit the conflicted files
- Add the resolved files:
git add <filename> - Continue the rebase:
git rebase --continue - (To abort the process:
git rebase --abort)
-
Push your changes (requires force push if the branch is already on remote):
git push --force-with-lease origin feature-branch
Common Issues
- Conflicts during rebase: Similar to merge conflicts, you’ll need to resolve them manually
- Lost commits: Rewriting history can cause commits to be lost if not done carefully
- Force push dangers: Using
--forcecan overwrite others’ changes; use--force-with-leaseinstead
Additional Notes
- Golden rule of rebasing: Never rebase branches that others are working on
- Use interactive rebasing to clean up your commits before sharing:
git rebase -i HEAD~3 # Rebase the last 3 commits - Interactive rebase options:
pick: Keep the commit as isreword: Edit the commit messagesquash: Combine with previous commitfixup: Combine with previous commit, discard the messagedrop: Remove the commit
When to Use Rebase vs. Merge
-
Use rebase when:
- You want a clean, linear history
- You’re working on a feature branch that only you use
- Before submitting a pull request, to incorporate latest changes
-
Use merge when:
- You want to preserve the complete history
- You’re working on a shared branch
- You want to clearly show where a feature branch was integrated