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.
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.
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.
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?
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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With