How to update a Git branch

Assuming you’ve been working on a feature branch:

$ git branch
* master
$ git checkout -b feature
Switched to a new branch 'feature'
# make some commits...

You find out there are some new commits on master:

$ git checkout master
$ git pull

And you want to merge them to your feature branch.

How would you go about doing that?


The simplest approach is to merge the changes:

$ git checkout feature
$ git merge master

If there are differences, then merge will apply the commits to the top of feature and create a new merge commit. Otherwise, the merge will be resolved by a fast-forward.


Alternatively, there’s rebase:

$ git checkout feature
$ git rebase master

Rebase, on the other hand, moves all diverging commits of feature to the top.

This means that the diverging commits will have new hashes because history will be rewritten.

Accordingly, if you’ve previously pushed your feature branch to remote, then the only way to update it is with force push:

$ git push origin feature --force

However, if developers have checked out your feature branch, then I don’t recommend this method. Stick with merge.

Please support this site and join our Discord!