Git - remote add origin vs remote set-url origin
How do these Git commands manage remote repositories differently? While both relate to configuring your Git remote, one is used for adding a new remote, and the other for changing an existing one. Let’s understand when and why you’d use each.
When working with Git, managing remote repositories is a common task. Two commands that often confuse beginners are:
- git remote add origin
- git remote set-url origin
Though they sound similar, they serve different purposes depending on your workflow.
git remote add origin
This command is used when you want to add a new remote to your local repository. Typically, it’s run once right after initializing a repo locally or cloning it without a remote. Here’s an example:
git remote add origin https://github.com/username/repo.git
- This sets the alias origin to point to your GitHub repository.
- Note: If origin already exists, this command will throw an error.
git remote set-url origin
This command is used to change the URL of an existing remote. It's helpful when:
- You’ve renamed your repository.
- You're switching from HTTPS to SSH.
- You’ve moved your repo to another hosting service.
Example:
git remote set-url origin git@github.com:username/repo.git
This updates the existing origin without having to delete or re-add it.
Summary
- Use add to define a new remote.
- Use set-url to update the URL of an existing remote.
- Don’t use add again if the remote already exists—it will throw an error.
- Understanding the difference helps you avoid conflicts and manage your remotes more efficiently in any Git-based project.