Push to 2 Git repositories at once and keep them in sync
By Flavio Copes
Learn how to push to two Git repositories at once and keep them in sync by adding a second push URL to your origin remote with git remote set-url.
You can push to two Git repositories with a single git push by adding a second push URL to your origin remote. Git then sends every push to both URLs, no extra work needed.
I had the need to have 2 GitHub repositories with the same exact content. Whenever I pushed my changes, those changes had to be sent to both repositories. This is useful for keeping a mirror, or a backup copy on a second account or a different Git host.
So here’s what I did.
Adding the second push URL
I already had a working repository with some code, set up as the origin remote in Git. I created a new empty repository on GitHub, then ran these two commands:
git remote set-url --add --push origin git@github.com:flaviocopes/original.git
git remote set-url --add --push origin git@github.com:flaviocopes/clone.git
That’s it. Now doing a git push sends the changes to both repositories.
Notice that the first command re-adds the original URL, even though it’s already the remote. That’s needed: the first set-url --add --push call replaces the default push URL instead of adding to it. Skip that line and you’d only push to the clone.
Verifying the setup
Check the result with git remote -v:
git remote -v
# origin git@github.com:flaviocopes/original.git (fetch)
# origin git@github.com:flaviocopes/original.git (push)
# origin git@github.com:flaviocopes/clone.git (push)
One fetch URL, two push URLs. Exactly what we want.
What this does not do
The sync is one-way. Fetching and pulling only talk to the fetch URL, which is still the original repository.
So if someone pushes a commit directly to the clone, your git pull will never see it, and the two repositories drift apart. Be careful with this: treat the second repository as a read-only mirror that only receives your pushes.
Also, the two pushes are independent. If the second one fails, say your key has no access to that repository, the first may have already succeeded. The fix is easy: sort out the access problem and run git push again. Git only sends what’s missing.
Undoing it
If you want to go back to a single repository, remove the extra push URL:
git remote set-url --delete --push origin git@github.com:flaviocopes/clone.git