Remotes and GitHub

How to add a Git remote

Point a local repository at a GitHub repo with git remote add origin so you can push commits there after git init on your machine.

An existing local repository does not automatically know where you want to publish it. You tell Git with git remote add.

You need this step when you built notes-project locally with git init and created the GitHub repository separately. Cloning skips it because git clone adds origin for you.

First, check whether a remote already exists:

cd notes-project
git remote -v

If the output is empty, add one:

git remote add origin [email protected]:flaviocopes/notes-project.git

This stores the URL under the name origin. It does not contact GitHub and it does not push any commits.

Verify the configuration:

git remote get-url origin
git remote -v

git status still shows the same working tree and local branch. Network state changes only when you fetch or push.

Your first push usually looks like:

git push -u origin main

The remote repository must exist on GitHub first, and your local branch needs at least one commit.

If you run git remote add when origin already exists, Git refuses:

error: remote origin already exists.

Stop and inspect the current URL with git remote -v. Do not delete it blindly. If the repository moved, update the URL instead:

git remote set-url origin [email protected]:flaviocopes/notes-project.git

A first push before any commits also fails:

error: src refspec main does not match any

Make at least one commit on main in notes-project, then push with -u.

Adding a remote with a typo in the URL does not fail immediately. The mistake shows up on push:

ERROR: Repository not found.

Fix the URL with git remote set-url origin and push again.

You can name a remote anything, not only origin. Some teams use upstream for the original repo and origin for a fork. The name is a label. The URL is what matters.

Try this on a disposable notes-project clone: inspect .git/config, add a second remote under another name, then remove it with git remote remove. Removing configuration does not delete local commits.

Lesson completed