git merge

This is your typical git merge. The commits from your new branch are put into the master branch as a single commit, but the branch where they were original created is still part of the tree, even if you delete that branch later, it will continue to be part of the commit history.

how git merge works

Sometimes this can get complex. On a large project, with several branches, it can become harder to understand the commit history.

git rebase

Now this is how git rebase works. We basically "re-write" history. It is as if the new branch never existed, their commits are simply moved to the master branch. You can see all the commits in the master branch in a linear fashion.

how git rebase works

When NOT to use rebase

You should never rebase commits that were previously pushed to a central repository and other people already based their work on them. If you think about it, git rebase rewrites history, so if you rebase commits that were already pushed and used by other people, you will be rewriting history that is being used by other people.

If you do this and then try to push the changes, the push will be rejected by the server and the error message will say you can use the --force flag to override this behavior, but you would do so at your own risk.

If you only rebase commits that were never pushed, you'll be fine. Even if you rebase commits that were pushed, but no one else based their work on them, you'll still be fine.

In practice

Before we start working, it's best if we check if there were any new commits to the master branch.

git checkout master
git pull

Then suppose you create a new branch to work on a new feature.

git checkout -b new-feature

You make a few changes and some commits to the new branch.

git add .
git commit -m "some changes"

Now you finished the work and are ready to merge the changes into the master branch. For that, we need to first pull from the master branch again to make sure it is up-to-date and that your changes will not cause any trouble.

git checkout master
git pull

To actually check if there are any conflicts, we go back to the new branch and do a rebase from master.

git checkout new-feature
git rebase master

This is what we were waiting for, we are now sure there are no conflicts, so we go into the master branch and place the changes there.

git checkout master
git rebase new-feature

And we are done, we can simply push everything to the remote master branch.

git push

Conclusion

Using git rebase or git merge for merging changes is still a matter of personal preference and culture, there are strong advocates on either side. Using git merge preserves the commit history, which is important for some people, and git rebase results in a cleaner, more linear, history, even if the real commit history was rather messy.