Sometimes, you need to push your code automatically to more than one repository. This is totally possible in git and here is how you do it.

Note: keep in mind that the most frequent use case assumes that all secondary repositories are only used for push; otherwise, you may have conflicts.

Check your current git copy

Before you can add another repository to push on, it is important to know which configuration you already have. In order to see where your current repo is syncing, type the following command:

Bash
cd <path_to_your_repo>
git remote -v

This should give you an output like:

Bash
origin https://xxx.git (fetch)
origin https://xxx.git (push)

where xxx is the url where your cod is stored. Note that if that command returns nothing, you don’t have set any remote repository to sync to.

Add a new remote location

Now that we have our origin configuration, we can easily add some more remote locations to push to using the following command:

Bash
git remote add <name_1> <url_1>
git remote add <name_2> <url_2>
...

git remote set-url --add --push <name_1> <url_1>
git remote set-url --add --push <name_2> <url_2>

Now executing the git remote -v command again should return:

Bash
origin https://xxx.git (fetch)
origin https://xxx.git (push)
<name_1> https://xxx.git (push)
<name_2> https://xxx.git (push)

Now I can choose which remote to push to when executing:

Bash
git push origin <BRANCH> # push on origin
git push <name_1> <BRANCH> # push on <name_1>
git push <name_2> <BRANCH> # push on <name_2>

Automatically push to multiple location at once

If I need to push automatically push to multiple location with one single command, I have to add multiple remote repositories using the same name. Here are the commands to execute:

Bash
git remote add origin <url_3>
git remote set-url --add --push origin <url_3>

git remote add upstream <url_4>
git remote set-url --add --push origin <url_4>

Now executing the git remote -v command again should return:

Bash
origin https://xxx.git (fetch)
origin https://xxx.git (push)
<name_1> https://xxx.git (push)
<name_2> https://xxx.git (push)
origin https://yyy.git (push) # <url_3>
origin https://yyy.git (push) # <url_4>

You can test using the command git push origin <BRANCH>. This should push your code to all branches named origin and having a reference for push.