1. Home
  2. Blog
  3. DevOps

DevOps

Git Remote Explained: Add, Set-URL, Rename, Remove and Push URLs

git remote manages the named connections between your local repository and the servers you push to and pull from. Learn how origin works, adding and listing remotes, changing URLs, separate push URLs, working with forks and an upstream remote, renaming and removing, pruning stale branches, and the credentials leak to avoid, all run in a real repository.

9 min read
Git remote explained: add, set-url, rename, remove and push URLs

Key takeaways

  • A remote is a named URL stored in your repository config; origin is just the default name used by git clone.
  • git remote add creates a remote, set-url changes it, rename and remove manage names.
  • A remote can have different fetch and push URLs, which git remote -v shows separately.
  • Never put a token in a remote URL: git remote -v printed our fake token in plain text.

Every git push and git pull needs to know where to send or fetch commits. Typing a full server URL each time would be painful, so Git lets you save URLs under short names called remotes. The git remote command manages those names. It is simple, but changing a repository’s URL after a migration, working with a fork and its original, or cleaning up deleted branches all depend on understanding it.

We ran every command with Git 2.56, using local bare repositories as stand-in servers so nothing touched the internet, a placeholder identity (Demo, demo@example.com), and fixed dates. Output is copied from those runs. For branch basics, see our git branch guide.

What is a Git remote?

A remote is a bookmark: a name such as origin that maps to a repository URL, plus rules for which branches to fetch. Remotes live in .git/config:

git config --get remote.origin.url
../server.git
git config --get remote.origin.fetch
+refs/heads/*:refs/remotes/origin/*

The fetch rule (a refspec) says: copy every branch on the server into a local read-only namespace refs/remotes/origin/. That is where remote-tracking branches such as origin/main come from. They are snapshots of the server, updated only when you fetch.

Our test setup

git init --bare server.git     # stands in for GitHub or GitLab
git init --bare backup.git     # a second server
git init -b main app           # our working repository

Bare repositories have no working files and are exactly what Git servers store, so they behave like real remotes for push and fetch, without any network or account.

Listing remotes

git remote -v
(none yet)

git remote lists names; -v adds the fetch and push URL for each. A freshly initialised repository has none. A cloned repository starts with one called origin, pointing at where you cloned from.

Adding a remote

git remote add origin ../server.git
git remote -v
origin	../server.git (fetch)
origin	../server.git (push)

git remote add origin ../server.git
error: remote origin already exists.

git remote add <name> <url> saves a new remote. If the name is taken, Git refuses, the error many people hit when following setup instructions in a repository that already has origin. In that case you want set-url, not add.

First push and upstream tracking

git push -u origin main
git branch -vv
* main 06960ab [origin/main] Initial commit

-u (short for --set-upstream) pushes and records origin/main as the branch your local main tracks. From then on, plain git push and git pull know where to go, and git status reports how far ahead or behind you are.

Inspecting a remote

git remote show origin
* remote origin
  Fetch URL: ../server.git
  Push  URL: ../server.git
  HEAD branch: (unknown)
  Remote branch:
    main tracked
  Local branch configured for 'git pull':
    main merges with remote main

git remote show contacts the server and summarises URLs, remote branches, which local branches track them, and stale branches. It is the best single command when pushes go somewhere unexpected.

Changing a remote URL

git remote set-url origin ../backup.git
git remote -v
origin	../backup.git (fetch)
origin	../backup.git (push)

git remote set-url upstream ../x.git
error: No such remote 'upstream'

When a repository moves, from one host to another, a renamed organisation, or HTTPS to SSH, update the URL in place with set-url. Tracking configuration stays intact, so nothing else needs changing. It only works for existing names, as the second command shows.

A separate push URL

git remote set-url --push origin ../backup.git
git remote -v
origin	../server.git (fetch)
origin	../backup.git (push)

A remote can fetch from one URL and push to another. Uses include fetching over anonymous HTTPS but pushing over SSH, or pushing to a mirror. This is also why git remote -v prints two lines per remote. You can even add several push URLs with set-url --add --push, so one push updates two servers.

Working with forks: origin and upstream

git remote add upstream ../backup.git
git remote
origin
upstream

When you fork a project, origin is your fork and, by convention, upstream is the original project. You fetch new changes from upstream, merge or rebase them into your branches, and push to origin to open pull requests. Keeping both remotes makes syncing a fork a two-command job: git fetch upstream, then git rebase upstream/main.

Renaming and removing remotes

git remote rename upstream mirror
git branch -r
  mirror/main
  origin/main

git remote remove mirror
git branch -r
  origin/main

rename updates the name and moves its remote-tracking branches, as mirror/main shows. remove (or rm) deletes the remote and all its remote-tracking branches from your local repository. It never deletes anything on the server.

Tip: git fetch --all updates every remote at once, handy when you work with both origin and upstream.

Pruning stale remote-tracking branches

When a teammate deletes a branch on the server, your origin/feature-x stays until you prune it. Run git fetch --prune (or git remote prune origin) to remove remote-tracking branches that no longer exist on the server. Set git config --global fetch.prune true to do it on every fetch. Pruning is safe: it only removes read-only snapshots, never your local branches.

HTTPS vs SSH remote URLs

Format Example Authentication
HTTPS https://github.com/org/repo.git Credential manager or personal access token
SSH git@github.com:org/repo.git SSH key
Local path ../server.git File permissions

Switching between them is just git remote set-url origin <new-url>. SSH avoids typing tokens once your key is set up; see our SSH keys guide.

The credentials leak to avoid

git remote add leaky https://user:SECRET123@example.com/repo.git
git remote -v
leaky	https://user:SECRET123@example.com/repo.git (fetch)
leaky	https://user:SECRET123@example.com/repo.git (push)

Embedding a token in a remote URL stores it in plain text in .git/config, and Git prints it whenever anyone runs git remote -v, shares a screenshot or pastes CI logs. (The token above is fake.) Use a credential helper, an SSH key, or in CI a token injected from a secret store through environment variables. If a token has ever been in a URL, revoke it.

Git remote cheat sheet

Task Command
List remotes with URLs git remote -v
Add a remote git remote add origin <url>
Change a URL git remote set-url origin <url>
Separate push URL git remote set-url --push origin <url>
Inspect git remote show origin
Rename git remote rename old new
Remove git remote remove name
Prune deleted branches git fetch --prune
Push and track git push -u origin main

The wider command set is in our Git commands cheat sheet.

Pushing to two servers at once, and checking with ls-remote

git remote add origin ../origin.git
git remote set-url --add --push origin ../origin.git
git remote set-url --add --push origin ../mirror.git
git remote -v
# origin  ../origin.git (fetch)
# origin  ../origin.git (push)
# origin  ../mirror.git (push)
git push origin main

git ls-remote origin
# a3d7d995c333...  HEAD
# a3d7d995c333...  refs/heads/main
git ls-remote ../mirror.git
# a3d7d995c333...  refs/heads/main      same commit on the mirror

A remote can have several push URLs, so one git push updates a main server and a backup mirror together. There is a trap here that we confirmed in a second repository: the moment you add any push URL, Git stops using the fetch URL for pushing. When we added only the mirror, the push went to the mirror and the original server received nothing. Add the original URL as a push URL first, then the extra one, exactly as above.

git ls-remote lists the branches and commits on a remote without fetching anything, which makes it a quick way to confirm that a push landed or that a URL works at all. git remote get-url --push --all origin prints every push URL, and with a second named remote added, git fetch --all updated both origin/main and mirror/main in one command. For automating mirror pushes in a pipeline, see our GitHub Actions CI/CD guide.

Final thoughts

git remote is the address book of your repository. Add origin once, use set-url when servers change, keep upstream alongside origin for forks, prune stale branches regularly, and keep credentials out of URLs. With those habits, pushing and pulling across any number of servers stays predictable. Automating pushes from CI is covered in our GitHub Actions guide.

Frequently asked questions

What is origin in Git?

origin is the default name Git gives to the remote you cloned from. It is just a name for a URL, and you can rename it or add other remotes.

How do I change the remote URL in Git?

Run git remote set-url origin followed by the new URL. Tracking branches and settings stay the same, so nothing else needs to change.

How do I fix remote origin already exists?

The repository already has a remote named origin. Use git remote set-url to change its URL, or add your new remote under a different name.

What is the difference between origin and upstream?

By convention origin is your own copy or fork, and upstream is the original project you forked from. You fetch from upstream and push to origin.

Does git remote remove delete the repository on the server?

No. It only removes the remote name and its remote-tracking branches from your local repository. The server repository is not touched.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Random Forest in Python: Bagging, Feature Sampling and OOB From Scratch

Random forest in Python from scratch: bootstrap sampling, feature sampling, number of trees, out-of-bag evaluation and impurity vs permutation importance.

Read article →
Software Development

MIME Types Explained: Content-Type, nosniff and a Common Types List

MIME types explained and tested in a browser: Content-Type, nosniff, scripts and stylesheets with wrong types, a common MIME types…

Read article →
DevOps

Git Clean Explained: Remove Untracked Files Without Regret

Git clean explained with dry runs: -n, -f, -d, -x, -X, exclusions, paths, nested repositories and interactive mode, plus a…

Read article →
Test Automation

Pytest approx: Comparing Floats With rel, abs and Collections

Pytest approx explained: default tolerances, the near-zero trap, rel and abs, lists and dicts, NaN, NumPy, and how it differs…

Read article →
Software Testing

Accessibility Testing: WCAG Checklist, Automated Tools and Manual Checks

Accessibility testing explained: WCAG basics, an axe-core scan of a broken and a fixed page, what automation missed, contrast checks…

Read article →
Databases & SQL

SQL UNPIVOT: Turn Columns Into Rows, 4 Ways Tested

SQL UNPIVOT explained: turn columns into rows with UNION ALL, CROSS JOIN with CASE, JSON functions or native UNPIVOT, with…

Read article →
Software Development

Intl NumberFormat in JavaScript: Currency, Compact, Percent and Units

Intl.NumberFormat in JavaScript: locales, currency, compact notation, percent, units, rounding, formatToParts, the non-breaking space trap and formatter reuse.

Read article →
Software Development

Python Abstract Class: ABC, abstractmethod and When to Use Them

Python abstract class explained: ABC and abstractmethod, abstract properties, shared logic with super, register, collections.abc and ABC vs Protocol, tested.

Read article →
Software Development

Python Subprocess Explained: run, Capture Output, Timeouts and Safety

Python subprocess explained with tested examples: run, capture_output, check, timeouts, input, environment, shell injection, encoding on Windows and Popen streaming.

Read article →
Databases & SQL

SQL EXPLAIN Plan: How to Read Query Plans and Fix Slow Queries

SQL EXPLAIN plan explained: read scans, index searches, covering indexes and temporary sorts, with before and after timings for five…

Read article →
Artificial Intelligence

Decision Tree in Python: Gini, Entropy and Overfitting From Scratch

Decision tree in Python from scratch: Gini impurity, entropy, information gain, best splits, readable rules, and how depth and leaf…

Read article →
Software Development

URL Query Parameters: Encoding, URLSearchParams and Common Traps

URL query parameters explained: reading and building them with URLSearchParams and urllib, percent encoding, plus signs, repeated keys and nine…

Read article →
DevOps

Git Blame Explained: Find Who Changed a Line, and Why

Git blame explained with a real repository: ignore whitespace, line ranges and functions, ignore-revs files for formatting commits, moved code…

Read article →
Test Automation

Pytest Benchmark: Measure Speed and Catch Performance Regressions

Pytest benchmark tutorial: the benchmark fixture, reading results, parametrized and pedantic benchmarks, saving baselines and failing the build on regressions.

Read article →
Software Testing

Defect Density: Formula, Worked Examples and How to Use It

Defect density explained: the formula, a five-module worked example, per KLOC vs per function point, severity weighting, defect removal efficiency…

Read article →
Databases & SQL

Case Insensitive Search in SQL: LOWER, LIKE, COLLATE and Indexes

Case insensitive search in SQL: LOWER, LIKE, COLLATE NOCASE and expression indexes compared with query plans, plus accented letters and…

Read article →
Databases & SQL

ON DELETE CASCADE in SQL: CASCADE vs SET NULL vs RESTRICT

ON DELETE CASCADE in SQL tested: CASCADE vs SET NULL vs RESTRICT, multi-level cascades, the SQLite foreign key pragma, row…

Read article →
Software Development

JavaScript BigInt Explained: Big Numbers, Division and JSON

JavaScript BigInt explained: the 2^53 limit, creating and converting BigInt, division, mixing types, JSON stringify and parse without losing digits,…

Read article →
Artificial Intelligence

Logistic Regression in Python: Sigmoid, Log Loss and Gradient Descent From Scratch

Logistic regression in Python from scratch: sigmoid, log loss, gradient descent, odds ratios, thresholds, sigmoid overflow and separable data, tested…

Read article →
DevOps

Git Worktree Explained: Work on Two Branches at Once

Git worktree explained: add, list, remove, prune, lock and detached worktrees, a hotfix workflow, and the errors you will hit,…

Read article →
Test Automation

Pytest ini Explained: addopts, markers, testpaths and Precedence

Pytest ini explained: testpaths, addopts, strict markers, xfail_strict, filterwarnings, minversion, config file precedence and command-line overrides, tested.

Read article →
Software Testing

Test Estimation Techniques: WBS, Three Point PERT and Monte Carlo

Test estimation techniques worked through: WBS, three point PERT, total uncertainty, a Monte Carlo check, percentage rules and Wideband Delphi.

Read article →
Databases & SQL

Gaps and Islands in SQL: Find Streaks and Missing Ranges

Gaps and islands in SQL: find login streaks and missing ranges with ROW_NUMBER, DENSE_RANK, LAG and LEAD, plus the duplicate…

Read article →
Databases & SQL

INSERT INTO SELECT in SQL: Copy Rows Between Tables Safely

INSERT INTO SELECT in SQL: copy rows between tables with chosen columns, joins and summaries, avoid duplicates on reruns, upsert,…

Read article →
Artificial Intelligence

Linear Regression in Python: Least Squares From Scratch, With R Squared

Linear regression in Python from scratch: closed form, NumPy least squares and gradient descent, R squared, RMSE, outliers and curved…

Read article →
DevOps

Git Remote Explained: Add, Set-URL, Rename, Remove and Push URLs

Git remote explained: add, set-url, separate push URLs, rename, remove and prune, plus how to avoid leaking tokens in remote…

Read article →
Test Automation

Pytest Mock: mocker.patch, spy, side_effect and autospec Explained

Pytest mock explained: mocker.patch, return_value, side_effect, spy, autospec and PropertyMock, with tested examples for APIs, clocks and retries.

Read article →
Software Testing

System Testing Explained: Types, Process and a Real End-to-End Example

System testing explained: types, entry and exit criteria, the process, and a real end-to-end test suite run against a small…

Read article →
Artificial Intelligence

Naive Bayes Classifier Explained: Build a Spam Filter in Python

Naive Bayes classifier explained by building a spam filter in Python: Bayes rule, the naive assumption, Laplace smoothing, log probabilities…

Read article →
DevOps

Git Branch Explained: Create, Switch, Rename, Delete and Recover

Git branch explained with tested commands: list, create, switch, rename, delete, merged checks, recovering deleted branches, remote tracking and naming.

Read article →
Test Automation

Pytest raises: Testing Exceptions, match and excinfo

Pytest raises explained with tested examples: match regexes, excinfo, custom and chained exceptions, parametrized error cases, pytest.warns and common mistakes.

Read article →
Software Testing

Non Functional Testing: Types, Metrics and a Real Load Test

Non functional testing explained: 10 key types, measurable requirements, latency percentiles and what a small real load test revealed about…

Read article →
Artificial Intelligence

K Means Clustering Explained: How It Works, With Python Code

K means clustering explained: the algorithm, a from-scratch NumPy version, choosing k with the elbow and silhouette methods, k-means++, scaling…

Read article →
DevOps

Git Log Explained: 15 Useful Commands and Pretty Formats

Git log explained with 15 tested commands: oneline, graph, filters by author, date, message and code, file history, stats, pretty…

Read article →
Test Automation

Pytest conftest.py Explained: Shared Fixtures, Hooks and Overrides

Pytest conftest.py explained with a tested suite: shared fixtures, scope and teardown, folder overrides, autouse, custom options, markers and useful…

Read article →
Software Testing

Usability Testing: Methods, Metrics, SUS Score and Checklist

Usability testing explained: methods, planning, writing tasks, running sessions, metrics, SUS scoring, how many users you need and a practical…

Read article →