October 07, 2020
Sometimes, you may want to sync your local Git repository to multiple remotes at once (e.g. Github and Gitlab).
You could do this by pushing twice, but it’s much easier to set up multiple push remotes in Git, and handle everything with one git push
.
Let’s say you want to push to two remotes, in this order:
git@github.com:username/example.git
git@gitlab.com:username/example.git
Go into your local Git repository, and remove the origin
remote if it exists:
git remote remove origin
Then, re-add it, with the first URL you want to push to (this will also act as your fetch
remote):
git remote add origin git@github.com:username/example.git
Next, set the URL of the first remote (this doesn’t visibly do anything, but is needed for the setup to work):
git remote set-url origin --add --push git@github.com:username/example.git
Then, add the URL of the second remote:
git remote set-url origin --add --push git@gitlab.com:username/example.git
And you’re done.
You can verify the setup with git remote -v
, which should print:
origin git@github.com:username/example.git (fetch)
origin git@github.com:username/example.git (push)
origin git@gitlab.com:username/example.git (push)
A push will happen in the order that you added the remotes (also in the order that they’re listed in the output above, so Github first, then Gitlab).
You can set the upstream reference for the master
branch with:
git push -u origin master
From now on, a git push
will push to both remotes.