Working with Remotes in Git

In order to collaborate with other users on a Git project, you should have an understanding on working with remotes in Git. Remote repositories are repositories that are hosted externally, most likely on the Internet. There are popular websites that provide this hosting service, such as Github and Bitbucket.

Essentially, the idea is that so you can push up code changes from your local machine to the remote, then other users can pull down and view those changes.

Using Git commands, remotes can be managed for a specific repository. To view the current remotes configured, run the git remote command.

If you haven’t set up a remote within a repository and run the command, nothing will happen. However if you have set up a remote, then you might see something like the following.

$ git remote

origin is the common name given to the remote repository. Websites such as Github and Bitbucket will provide instructions on how to set up a Git repository.

Usually, they will provide you with two commands: the first to initialise an empty Git repository in a given directory, and the second to add a remote.

$ git init
$ git remote add origin

You do not have to name the remote origin, although it is common to do so when working with only one remote. For example, to name the remote some_remote_name:

$ git remote add some_remote_name

You can also specify -v to show the URLs that Git has stored for the remote name to be used when reading and writing to that remote.

$ git remote -v
some_remote_name (fetch)
some_remote_name (push)

When a remote has been added, you can push your changes up to it by passing in the remote name and the branch name to git push.

$ git push some_remote_name master

A Git repository can have many remotes, if you need to push changes to multiple locations. Simply use the git remote add command again specifying the remote shortname and URL.

$ git remote add github

This will allow you to push changes either to the some_remote_name or the github remote.

$ git push -u some_remote_name master
$ git push -u github master

Renaming a remote is possible. Simply run git remote rename passing in the current remote name as the first argument, followed by the name you would like the remote to be changed to as the second.

$ git remote rename some_remote_name another_remote_name

Should you wish to remove a remote, you can either use git remote remove or git remote rm passing in the shortname of the remote.

$ git remote rm another_remote_name