To collaborate with a team or backup your project history, you need to link your Local Repository (the .git folder on your machine) to a Remote Repository (a centralized copy hosted on a server like GitHub or GitLab).
1. The Remote Repository Concept
A remote repository serves as the central source of truth for a project. When you interact with a remote, you typically use a shorter alias to refer to its full URL.
- Origin: This is the conventional alias used by Git to refer to the main remote repository that you cloned from or pushed to first.
2. Adding a Remote (git remote add)
The git remote add command establishes the connection between your local repository and the remote server URL.
Execution Example: Adding ‘origin’
After creating an empty repository on GitHub (or another service), they provide you with the command to link your local project.
git remote add origin git@github.com:username/my-project.git
| Component | Description |
git remote add | The command to create a new remote alias. |
origin | The chosen name/alias for the remote (conventional name). |
git@github.com:username/my-project.git | The full URL (usually SSH or HTTPS) of the remote repository. |
3. Viewing Remote Connections
You can use the git remote command to check which remote repositories your local project is connected to.
Listing Remotes
To list the short names of all configured remotes:
git remote
Viewing Remote Details (URLs)
The -v (verbose) flag shows the URL associated with each remote name, indicating both the fetch (download) and push (upload) URLs.
git remote -v
4. Renaming and Removing Remotes
Managing remotes is important if you change hosting services or need to clean up unused connections.
Renaming a Remote
To rename the origin remote to a new name, for instance, github:
git remote rename origin github
Removing a Remote
To remove a remote connection entirely:
git remote remove github
5. Cloning an Existing Remote Repository
If a project already exists on GitHub, you don’t use git init. Instead, you use git clone, which performs multiple actions in one step:
- Downloads the entire project, including the full history.
- Initializes the project directory as a local Git repository.
- Automatically adds the remote URL and names it
origin. - Checks out the
mainormasterbranch.
Execution Example: Cloning
git clone https://github.com/username/existing-repo.git
