Rebase Master

serhatteker profile image Serhat Teker Originally published at tech.serhatteker.com on ・2 min read


While you've been working on something, probably you've been working on a branch on-and-off, or lots has happened in other branches.

The best solution would be to rebase your branch onto master. This keeps the history tidy and makes things a lot easier to follow.

Update your feature branch from master:

  1. Switch the master branch
  $ git checkout master
  1. Get remote updates:
  $ git pull
  1. Switch back to your local branch:
  $ git checkout local_branch
  1. Make the rebase magic:
  $ git rebase master
  1. Push your local branch to remote:
  $ git push

--force flag will be needed if you've already pushed your branch.

  $ git push --force

*Warning* : Think and check twice before doing this.

comparing branches

If you want to compare your local and remote feature branch before "forced push":

$ git diff <master_branch_path> <remote_branch_path>

For example:

$ git diff feature origin/feature

Where feature is your local branch and origin/master is your remote branch.

Git - Your branch and 'origin/xxx' have diverged

If you receive below error:

Your branch and 'origin/xxx' have diverged,
and have 1 and 1 different commit(s) each, respectively.

It is normal. This happens if you rebase the branch which was previously pushed to the origin repository. Rebase rewrites history, so after it you'll have different local and remote state.

We had a history like this:

... o ---- o ---- A ---- B  master, origin/master
                    C  branch_xxx, origin/branch_xxx

And we "rewrote" the history like this:

... o ---- o ---- A ---------------------- B  master, origin/master
                   \                        \
                    C  origin/branch_xxx     C` branch_xxx

The solution:

$ git push origin branch_xxx --force

So the actual state will be like:

... o ---- o ---- A ---- B  master, origin/master
                           C` branch_xxx, origin/branch_xxx

As said before:

*Warning* : Think and check twice before doing this.

For more details:

git-scm — Git Branching - Rebasing


Editor guide