git merge vs. git rebase
Git Merge and Git Rebase commands solves the same problem.
Both are integrating changes from one branch into another, just in a different way.
You work on a feature branch. Another colleague pushes code into the main branch.
The new commits in main are relevant to your feature branch. To get the new commits into your feature branch you can run ‘git merge’ or ‘git rebase’.
The Merge Option: git merge
The easiest option is to merge the main branch into the feature branch.
git checkout feature
git merge main
This also means that the feature branch will have an external merge commit every time you need to incorporate main changes.
This can pollute your feature branch’s history.
It may be harder to understand the history of the project.
The Rebase Option: git rebase
As an alternative, you can rebase (neu ausrichten auf deutsch) the feature branch onto the main branch using the following commands
git checkout feature
git rebase main
This moves the feature branch to begin on the tip of the main branch, integrating all of the new commits in main.
Rebasing re-writes the project history by creating brand new commits for each commit in the original branch.
The biggest benefit is a much cleaner project history.
It eliminates the unnecessary merge commits required by git merge.
The disadvantage is that you can’t see when upstream changes (main) were incorporated into the feature.
Interactive Rebasing
With interactive rebasing you can alter commits as they are moved to the new branch. You can avoid messy history before merging a feature branch into main.
git checkout feature
git rebase -i main
This will open a text editor listing all of the commits that are about to be moved.
For example, if the 2nd commit fixes a small problem in the 1st commit, you can condense them into a single commit with the fixup command:
If you prefer a clean, linear history free of unnecessary merge commits, you should reach for git rebase instead of git merge.
On the other hand, if you want to preserve the complete history of your project and avoid the risk of re-writing public commits, you can stay with git merge.
Further reading here: