Sam Hooke

Managing multiple remotes in Git

Following are some quick notes on how to manage using multiple remotes in Git.

What are remotes? §

Remotes specify other repositories to which we can push or pull commits. Before pushing to or pulling from another repository, we must add it as a remote, identified by a name of our choice. By convention, origin is typically the name for the default remote. Multiple remotes can be defined.

Add a new remote §

Create a new remote named some_org_repo which identifies the specified repo:

git remote add some_org_repo https://github.com/org_name/repo_name.git

Managing branches to track remotes §

Each branch can have its own remote specified. The remote can be specified when the branch is first created, or can be updated at any later point.

Start tracking a new remote branch §

Create a new branch which tracks branch feature_x from remote some_org_repo, and switch to that branch:

git checkout --track some_org_repo/feature_x

Update existing branch to track remote branch §

Update the currently checked out branch to track branch feature_x from remote some_org_repo:

git branch -u some_org_repo/feature_x

If you get the following error:

error: the requested upstream branch 'some_org_repo/feature_x' does not exist
hint:
hint: If you are planning on basing your work on an upstream
hint: branch that already exists at the remote, you may need to
hint: run "git fetch" to retrieve it.
hint:
hint: If you are planning to push out a new local branch that
hint: will track its remote counterpart, you may want to use
hint: "git push -u" to set the upstream config as you push.

Assuming you have the branch name correct, this error is probably because you do not yet have a local copy of the remote branch. This may be resolved by running the following and then retrying the command:

git fetch some_org_repo

Pushing and pulling §

By default, pushing or pulling on a branch will push to or pull from that branch’s remote. However, we can explicitly specify the remote in order to override which remote to push to or pull from.

Pushing to the tracked remote §

Assuming the current branch’s remote is some_org_repo, this will push commits to the remote some_org_repo:

git push

Pushing to a different remote §

Regardless of what the current branch’s remote is, this will push commits to the remote origin:

git push origin

Pulling changes from the tracked remote §

Assuming the current branch’s remote is some_org_repo, this will pull commits from the remote some_org_repo:

git pull

Pulling from a different remote §

Regardless of what the current branch’s remote is, this will pull commits from the remote origin:

git pull origin