How to push a Git repo to multiple remotes

Subscribe to my newsletter and never miss my upcoming articles

Git is an indispensable tool for a developer. But what if you have a local code repository that you need to push to multiple remote repositories (e.g. GitHub and Bitbucket).

Well, one solution is to set multiple upstream for a repository and push to them separately.

Another solution is to keep both the remote repositories in sync and update both repositories with a single push command.

Let's look at the first solution.

First, let’s clone the existing remote Git repository. CD into your directory where code is located and run the following command:

git init

This will initialize the git repository. So, now we have a local git repository.

Now we need to tell the local repository to connect to a remote upstream:

git remote add origin git@github.com:[username]/[repository]

You can check all the current remotes by running the following command:

git remote -v

It should show you only one remote named origin.

Now let’s add another remote to the current local repository:

$ git remote add remote_name remote_url

e.g.

git remote add github http://github.com/path/to/repo

Now you can push to the main remote branch as:

git push origin <branch-name>

And you can push to the new remote branch as:

git push github <branch-name>

Now let’s look at the second solution:

We can push to multiple remotes at once by setting multiple remotes. This is will allow us to push to many remotes with a single git push.

First, we need to clone our repository, or create one fresh and configure it like a single remote as origin.

git remote add origin git@github.com:[username]/[repository]

Now let’s set the multiple remote URLs including the one we already set above.

git remote set-url --add --push origin git@github.com:[username]/[repository]
git remote set-url --add --push origin git@bitbucket.org:[username]/[repository]

To check for the above changes, type:

git remote -v

It should show us something like this:

origin    git@github.com:[username]/[repository] (fetch)
origin    git@github.com:[username]/[repository] (push)
origin    git@bitbucket.org:[username]/[repository] (push)

So, now a git fetch or git pull will fetch from the first URL in that list, and a git push will push to all push URLs. I find this a really useful solution to use if you’ve got a repository mirrored on GitHub and Bitbucket or other places and you want to keep both the upstream in sync.

No Comments Yet