Adding a remote repository in Git?

In this tutorial, I will explain how to add a new remote repository, a branch, and file in the remote repository from the terminal (Git Bash).

Adding the remote repo

If you are working on Git terminal then you may check the current repo (if any is added/set) by using this command:

$ git remote –v

This should display the URL of the current remote repository as shown below for our test purpose:

Git remote add repo

If you require adding a new repository then use the git remote add command as follows:

$ git remote add origin

For example, this command adds our test remote repository (bootstrap.git):

$ git remote add origin

If Git terminal returns a fatal error message like this:

fatal: remote origin already exists.

You may use some other name than the origin. For example:

$ git remote add my_bootstrap

For testing, if the remote repo is added or not, run the remote –v command again i.e.

$ git remote –v

The result with our test:

Git remote add

You can see the remote repo with the name of my_bootstrap is added.

Did you Know? The origin is just an alias to the remote repository. You may use any other name as an alias as in above example for the remote repositories. Similarly, you may use other commands with that name other than origin .e.g git push origin/other_name etc.

How to add a branch while having multiple repositories?

In this section, I will show you how to add a branch in a remote repository while having multiple branches.

For that, first I added another repository by using this command:

$ git remote add my_test

So, we have now three repositories as shown below:

my_bootstrap (fetch)

my_bootstrap (push)

my_test (fetch)

my_test (push)

origin (fetch)

origin (push)

Our target is to create a new branch, adding a file in the my_test repository. The branch name is “tst_multiple_br” and I will add a text file (tst1.txt).

First, creating the branch locally:

$ git branch tst_multiple_br

This is followed by checking out this branch:

$ git checkout tst_multiple_br

Now add the text file in that branch locally:

$ git add tst1.txt

Committing the file added:

$ git commit -m “File added for multiple repo test”

And finally pushing this branch and file in our target remote repository i.e. my_test

$ git push my_test tst_multiple_br

All these commands in the terminal with output:

Git remote add local

This is the online view of the remote repository after adding the branch/file:

Git remote repository