Git is a decentralized version control system, which means your local repo is the same thing as the remote repository on a site like Github. When you need to push or pull changes, you must do so using a Git remote.
What Are Git Remotes?
Because Git is a decentralized service, where local and remote repos use the same system, your local repository has no idea what the current state of your Github repo is, and vice versa. To communicate, Git clients must set up remotes to push and pull data from.
A remote is basically a URL with a name, but it’s a bit more complicated than that. Because you choose when to run
git pull and
git push, you can actually have multiple Git remotes. This can be useful to manage a development repository and release repository on a different platform, such as cloud-specific solutions like AWS CodeCommit.
New changes from other people in your repository must be fetched from the remote. This includes changes to your working branch, but also can fetch changes on other branches still in progress. When you need to commit something, such as adding to the HEAD or making a new branch, you must also push to the remote.
Managing Git Remotes
When you first clone or download a Git repository from the internet, it likely is configured with a remote called “origin.” You can verify this by listing the remotes, with the
-v flag for verbose, which displays the URL as well:
git remote -v
If you want to switch remotes, like in the case of forking a Github repo and pushing updates to your own repo, you’ll need to delete the old remote:
git remote rm origin
Then, you can add a new remote. If you’re setting up a new Git repo after running
git init, you will need to do this as well, since you won’t have a remote by default. The exact URL will depend on the service you’re using, but for Github, it’s available under “Code” on the main repo page. You can choose to connect over HTTPS or SSH.
Once you have the URL, you can add it with a name, usually “origin” if this is the primary remote:
git remote add origin https://github.com/username/reponame.git
Once set up, you can push and pull from it by specifying the remote name, and remote branch:
git push remote master git fetch/pull remote master
Pushing a Branch to a Different Remote
You can configure a default remote, which is usually set up to be origin. This is why, when pushing for the first time, you must set an upstream:
git push --set-upstream origin/master
However, you can also configure the upstream for individual branches.
git switch releasebranch git branch --set-upstream-to=release/master
Here, Git will set the upstream used for the
releasebranch to be “release,” which can be configured to a separate repository.