4. Remotes & Syncing

Once you have a local Git repository on your machine and an empty repository hosted on GitHub, you need to connect them. In this chapter, we will learn how to add remotes, synchronize histories, and establish upstream tracking.

1. Linking Local and Remote Repositories

When you create an empty repository on GitHub, it will display a page showing a set of setup terminal commands. To link an existing local repository to this remote, run:

git remote add origin git@github.com:username/repo-name.git

Let's break down this command:

  • git remote add: Adds a new remote reference to your local config.
  • origin: The alias name for the remote. By convention, the primary remote is always named "origin".
  • git@github.com:username/repo-name.git: The SSH URL of your GitHub repository.

2. Verifying Remote Connections

To verify that your local repository has successfully saved the remote address, run:

git remote -v

This should print two lines (one for fetching, one for pushing):

origin  git@github.com:username/repo-name.git (fetch)
origin  git@github.com:username/repo-name.git (push)

3. Pushing to GitHub: The -u Upstream Flag

The first time you upload commits from your local default branch (e.g., main) to GitHub, you need to specify the remote name and the branch. We also include the -u flag:

git push -u origin main

The -u (or --set-upstream) flag tells Git to remember the connection between your local main branch and the main branch on the origin server. Once this upstream tracking is established, you no longer need to type the full command! For all future syncs, simply type:

git push

4. Fetching vs. Pulling

When collaborating on GitHub, other developers will push changes to the repository. To sync your local machine with those cloud changes, you have two operations:

A. Fetching: git fetch

Downloads all branches, commits, and tags from GitHub, but does **not** merge them into your local files. It is a safe, non-destructive read-only operation:

git fetch origin

B. Pulling: git pull

Downloads remote changes and immediately merges them into your active branch:

git pull origin main
Best Practice Tip: Always pull with rebase to keep your commit logs clean and prevent messy merge commits:
git pull --rebase origin main

5. Renaming a Remote Reference

If you ever need to change the URL of your remote server (for example, if you move your project from Bitbucket to GitHub):

git remote set-url origin git@github.com:username/new-repo-name.git