Rebasing and Merging

Let’s begin with the most foundational part of learning Git, the open source tool universally used to write modern software: Merging vs. rebasing.

When you are using git, the first command you will learn is git checkout.

Rebase Against Main

git rebase -i main

Next, let’s meet the interactive rebase against main.

Force Pushes

--force-with-lease

If you’ve made any rebase or squash, your commit history will have diverged. That means the commits you have locally will be different than the ones on Github or Gitlab. (You can check this by examining the commits with git show.)

When this happens, you’ll need to force push onto Github. Force pushing means you will replace all of the commits on Github’s branch, overwriting them with your own. But for safety, always use the --force-with-lease, which automatically checks to make sure that all of the remote branch’s commits have already been incorporated into your code.

This means that if another developer has pushed commits on the same branch, Git will fail.

The alternative option is to use --force (with no “lease”), but this is always dangerous when working on a team. If another developer has added commits even in just the few minutes it took you between pulling and rebasing, you will overwrite them using --force.

Pulling with Rebase

git pull --rebase

Here, we will Git to pull the remote branch from Github and also rebase any commits different from the remote onto it.