git rebase – practical guide
What is git rebase
?
git rebase
allows you to rewrite commit history by moving, combining, or modifying commits. It eliminates unnecessary merge commits, helping to create a clean, linear project history.
By understanding and properly using git rebase
, you can maintain a tidy and comprehensible repository, ensuring smoother collaboration and easier debugging.
Examples
1. Rebase feature-branch onto main
git rebase main
on feature-branch:
Before rebase:
After rebase:
2. Interactive rebase (squashing commits)
git rebase -i
with squashing:
Before rebase:
After rebase:
3. Rebase --onto (changing branch base)
git rebase --onto new-base old-base feature-branch
:
Before rebase:
After rebase:
When to use/not use git rebase
?
When to use git rebase ? | When not to use git rebase ? |
---|---|
✅ Before merging into main - to avoid unnecessary merge commits. | ❌ On a shared branch – it rewrites commit history, which can cause conflicts. |
✅ Before code review, to clean up commits: ( git rebase -i ) | ❌ If commits were already pushed – requires git push --force , which may overwrite others' changes. |
✅ To rebase a branch onto a different base: ( git rebase --onto ) | |
✅ During git pull , to avoid merge commits: ( git pull --rebase ) |
Conclusion
git rebase
helps keep history clean but should be used carefully. Use it when you want to avoid unnecessary merge commits and maintain a tidy repository.