Synching a git fork
This post is about to sync a fork of a repository to keep it up-to-date with the upstream (the fork base) repository.
The Setup
Before you can sync, you need to add a remote that points to the upstream repository. You may have done this when you originally forked.
Tip: Syncing your fork only updates your local copy of the repository; it does not update your repository on GitHub.
# List the current remotes$ git remote -vorigin https://github.com/user/repo.git (fetch)origin https://github.com/user/repo.git (push)# Set a new remote$ git remote add upstream https://github.com/otheruser/repo.git# Verify new remote$ git remote -vorigin https://github.com/user/repo.git (fetch)origin https://github.com/user/repo.git (push)upstream https://github.com/otheruser/repo.git (fetch)upstream https://github.com/otheruser/repo.git (push)
Syncing
There are two steps required to sync your repository with the upstream: first you must fetch from the remote, then you must rebase or merge the desired branch into your local branch.
Fetching
Fetching from the remote repository will bring in its branches and their respective commits. These are stored in your local repository under special branches.
# Fetch all the branches of that remote into remote-tracking branches,# such as upstream/master:$ git fetch upstream# Make sure that you're on your master branch:git checkout master
We now have the upstream's master branch stored in a local branch, upstream/master
# List all local and remote-tracking branches$ git branch -va* master a422352 My local commitremotes/origin/HEAD -> origin/masterremotes/origin/master a422352 My local commitremotes/upstream/master 5fdff0f Some upstream commit
Rebase
Last step is to rebase your branch and push the changes to your branch.
# rebasegit rebase upstream/master# push changes to githubgit push -f origin master
You only need to use the -f the first time after you've rebased.
If you don't want to rewrite the history of your master branch, (for example because other people may have cloned it) then you should replace the last command with git merge upstream/master. However, for making further pull requests that are as clean as possible, it's probably better to rebase.