Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge local master branch with remote master branch in Git

Tags:

git

git-merge

People also ask

How do I merge local and remote branch changes?

Merge a Remote Branch to a Local Branch in Git by Tracking and Pulling Changes on the Remote Repository. We will now clone a remote repository containing two branches, master and gh-pages . Then, we will create a local branch another-branch and set it to track any and pull changes made on the remote main branch.

Can I merge a local branch to master?

First we run git checkout master to change the active branch back to the master branch. Then we run the command git merge new-branch to merge the new feature into the master branch. Note: git merge merges the specified branch into the currently active branch. So we need to be on the branch that we are merging into.


Case 1: remote/master has everything that local master has

If remote/master contains all of the commits that the local master contains, simply do a git pull:

git checkout master
git pull remote master

You can check if the local master has commits that remote/master doesn't by using the following:

git fetch remote
git log --oneline --graph remote/master..master

That will show you all commits that are contained in master but not in remote/master. If you don't see any output, that means remote/master has everything that the local master has.

Case 2: local master has commits that remote/master doesn't have

If the local master contains commits that remote/master doesn't contain, you'll have to figure out how you want to handle that. Do you want to keep them and merge them with remote/master, or do you simply want to throw them away?

Case 2a: merge/rebase local master commits into remote/master

If you want to keep them, you can either merge or rebase the local master with remote/master:

git checkout master
git fetch <remote>

# Merge remote/master
git merge remote/master

# Or rebase local commits on top instead
git rebase remote/master

# Push the results
git push remote master

Case 2b: throw away local master commits

If you don't want to keep the local commits, then just do a hard reset of the local master to the same point as the remote/master:

git checkout master
git fetch remote
git reset --hard remote/master

Documentation

You can read more about all of these commands from the Git documentation. I also highly recommend the excellent free online Pro Git book, especially chapters 1-3 and 6-6.5.