If you are very familiar with open source technologies, you must have used git
commands before. git merge
and git rebase
commands are git
commands that are very similar in the sense that they offer the same result, but the key difference is in the way they achieve these results. This key difference between the Merge vs Rebase, two commands is what we shall look into in this post.
Illustration
Lets say we are working on a project in our git repository, on the master branch created after our first commit, we have ‘ABC’, we make the b BOLD making the sequence ‘ABC’. On one of the feature branches, we make the c BOLD making the sequence to become ‘ABC‘. Now, let us see how these changes would be handled by git merge
and git rebase
ABC FEATURE / / ABC---ABC MASTER
Git Merge
This is the easiest way to merge a feature branch to the master branch is by using the following command.
git merge master feature
This joins the two histories together by replaying the changes that occurred on your feature branch after it diverged on top of the master branch. This is then recorded in a new commit, preserving the ancestry of each commit. Our illustration would now be like this for merge:
ABC FEATURE / \ / \ ABC---ABC---ABC MASTER
PROs
- Your history is always safe.
- You can easily retrace your steps.
- Ideal for working in teams.
CONs
- Too many merges
- History can become really clustered.
- Risk of pitfalls is really high.
Git Rebase
This is the next alternative to merging.
git checkout feature git rebase master
Here, rebasing can be understood as “moving the base of a branch onto a different position”. This moves the entire feature
branch to begin on the tip of the master
branch, effectively incorporating all of the new commits in master
. But, instead of using a merge commit, rebasing re-writes the project history by creating brand new commits for each commit in the original branch. Our illustration would now be like this for rebase:
ABC---ABC FEATURE / / ABC---ABC MASTER
PROs
- Clean and void of unnecessary commits
- Effective for personal projects/private repositories.
- Useful for keeping a linear commit history.
CONs
- It is not advisable to use in Public repositories.
- It does not preserve project’s history.
- Rebasing and
pull
requests do not go well together. - Reducing commits ends up hiding plenty contexts.
- Risk of breakage.
Conclusion
Experts recommend that:
- Merging is advisable for public projects that has a team working on it.
- Merging is the safest option to use as beginners and amateur users of git
- If you value a more clean and straight-line history, use rebase.
- If you value clarity and traceability of history, always merge.