When to use 'git pull --rebase'

Redowan Delowar July 14, 2022
Source

Whenever your local branch diverges from the remote branch, you can't directly pull from the remote branch and merge it into the local branch. This can happen when, for example:

  • You checkout from the main branch to work on a feature in a branch named alice.
  • When you're done, you merge alice into main.
  • After that, if you try to pull the main branch from remote again and the content of the main branch changes by this time, you'll encounter a merge error.

Reproduce the issue

Create a new branch named alice from main. Run:

From alice branch, add a line to a newly created file foo.txt:

Add, commit, and push the branch:

From the GitHub UI, send a pull request against the main branch and merge it:

GitHub pull request UI showing merge from alice branch to main

In your local machine, switch to main and try to pull the latest content merged from the alice branch. You'll encounter the following error:

This means that the history of your local main branch and the remote main branch have diverged and they aren't reconciliable.

Solution

From the main branch, you can run:

This will rebase your local main by adding your local commits on top of the remote commits.

Further reading

Discussion in the ATmosphere

Loading comments...