How to change remote git

How to change remote git

How can I change the remote/target repository URL on Windows? [duplicate]

I created a local GIT repository on Windows. Let’s call it AAA. I staged, committed, and pushed the contents to GitHub. git@github.com:username/AAA.git

I realized I made a mistake with the name.

On GitHub, I renamed it to git@github.com:username/BBB.git

Now, on my Windows machine, I need to change git@github.com:username/AAA.git to git@github.com:username/BBB.git because the settings are still trying to «push» to git@github.com:username/AAA.git but I need to push to git@github.com:username/BBB.git now.

How could I do that?

4 Answers 4

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

How to change remote git. Смотреть фото How to change remote git. Смотреть картинку How to change remote git. Картинка про How to change remote git. Фото How to change remote git

How to change remote git. Смотреть фото How to change remote git. Смотреть картинку How to change remote git. Картинка про How to change remote git. Фото How to change remote git

On my machine in a repo I regularly use it looks like this:

The line you see commented out is an alternative address for the repository that I sometimes switch to simply by changing which line is commented out.

This is the file that is getting manipulated under-the-hood when you run something like git remote rm or git remote add but in this case since its only a typo you made it might make sense to correct it this way.

How to change remote git repository

In this article we’ll follow simple steps to change a remote Git repository using the command line.

Table of Contents

1. List your existing remotes

To list the existing remotes we open the terminal and type in the following command:

If you copied the link to the repository from Clone with SSH in your GitLab, the output should look something like this:

If you copied the link to the repository from Clone with HTTPS in your GitLab, the output should look something like this:

Note: To find the SSH and HTTPS URLs, go to your GitLab, select your project, and click on Clone.

How to change remote git. Смотреть фото How to change remote git. Смотреть картинку How to change remote git. Картинка про How to change remote git. Фото How to change remote gitgitlab repository with ssh/https links

2. Change a remote Git repository

We can change the remote repository by using git remote set-url command:

The command takes two arguments: existing name of the remote (in our case origin) and a new remote URL (in our case This email address is being protected from spambots. You need JavaScript enabled to view it. :user/repository2.git)

In case you change your remote repository to https URL, you will be prompted for your username and password next time you use git fetch, git pull or git push.

If you try to use a link to a non-existing remote, you will get the following error:

When this happens, recheck your URL and make sure it matches the one in your GitLab or GitHub.

If you’d like to learn about Git make sure to check the following articles:

About remote repositories

In this article

GitHub’s collaborative approach to development depends on publishing commits from your local repository to GitHub for other people to view, fetch, and update.

About remote repositories

A remote URL is Git’s fancy way of saying «the place where your code is stored.» That URL could be your repository on GitHub, or another user’s fork, or even on a completely different server.

You can only push to two types of URL addresses:

Creating remote repositories

You can use the git remote add command to match a remote URL with a name. For example, you’d type the following in the command line:

You can use the command git remote set-url to change a remote’s URL.

Choosing a URL for your remote repository

There are several ways to clone repositories available on GitHub.com.

When you view a repository while signed in to your account, the URLs you can use to clone the project onto your computer are available below the repository details.

For information on setting or changing your remote URL, see «Managing remote repositories.»

Cloning with HTTPS URLs

The https:// clone URLs are available on all repositories, regardless of visibility. https:// clone URLs work even if you are behind a firewall or proxy.

If you are accessing an organization that uses SAML SSO, you must also authorize your personal access token to access the organization before you authenticate. For more information, see «About authentication with SAML single sign-on» and «Authorizing a personal access token for use with SAML single sign-on.»

Tips:

If you’d rather use SSH but cannot connect over port 22, you might be able to use SSH over the HTTPS port. For more information, see «Using SSH over the HTTPS port.»

Cloning with SSH URLs

SSH URLs provide access to a Git repository via SSH, a secure protocol. To use these URLs, you must generate an SSH keypair on your computer and add the public key to your account on GitHub.com. For more information, see «Connecting to GitHub with SSH.»

If you are accessing an organization that uses SAML single sign-on (SSO), you must authorize your SSH key to access the organization before you authenticate. For more information, see «About authentication with SAML single sign-on» and «Authorizing an SSH key for use with SAML single sign-on» in the GitHub Enterprise Cloud documentation.

Tip: You can use an SSH URL to clone a repository to your computer, or as a secure way of deploying your code to production servers. You can also use SSH agent forwarding with your deploy script to avoid managing keys on the server. For more information, see «Using SSH Agent Forwarding.»

Cloning with GitHub CLI

You can also install GitHub CLI to use GitHub workflows in your terminal. For more information, see «About GitHub CLI.»

Cloning with Subversion

You can also use a Subversion client to access any repository on GitHub. Subversion offers a different feature set than Git. For more information, see «What are the differences between Subversion and Git?»

You can also access repositories on GitHub from Subversion clients. For more information, see «Support for Subversion clients.»

Help us make these docs great!

All GitHub docs are open source. See something that’s wrong or unclear? Submit a pull request.

How to change the remote repository for a git submodule?

I’ve created a git repository with a submodule in it. I’m able to tell the submodule itself to change its remote repository path, but I’m not sure how to tell the parent repository how to change the remote repository path for the submodule.

I wouldn’t be surprised if I’m somewhat out of luck and have to do things manually, as even deleting submodules isn’t easy.

How to change remote git. Смотреть фото How to change remote git. Смотреть картинку How to change remote git. Картинка про How to change remote git. Фото How to change remote git

9 Answers 9

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

If repo history is different then you need to checkout new branch manually:

With Git 2.25 (Q1 2020), you can modify it.
See «Git submodule url changed» and the new command

Warning: Hi-Angel mentions in the comments (tested even with Git 2.31.1):

One should be careful with git submodule set-url because it has a bug:

Original answer (May 2009, ten years ago)

Actually, a patch has been submitted in April 2009 to clarify gitmodule role.

So now the gitmodule documentation does not yet include:

That pretty much confirm Jim’s answer.

» git submodule sync » has been added in August 2008 precisely to make that task easier when URL changes (especially if the number of submodules is important).
The associate script with that command is straightforward enough:

The goal remains: git config remote.»$remote».url «$url»

Синхронизация в Git

В системе SVN используется единый централизованный репозиторий, служащий центром связи для разработчиков. Совместная работа ведется путем передачи наборов изменений между рабочими копиями разработчиков и центральным репозиторием. Однако модель распределенной совместной работы в Git предполагает, что каждый разработчик использует собственную копию репозитория со своей локальной историей и структурой веток. Обычно пользователи делятся не отдельными наборами изменений, а сериями коммитов. Вместо того чтобы выполнять коммит одного набора изменений из рабочей копии в центральный репозиторий, Git позволяет передавать между репозиториями целые ветки.

git remote

Команда git remote позволяет создавать, просматривать и удалять подключения к другим репозиториям. Удаленные подключения скорее похожи на закладки, чем на прямые ссылки на другие репозитории. Они служат удобными именами, с помощью которых можно сослаться на не очень удобный URL-адрес, а не предоставляют доступ к другому репозиторию в режиме реального времени.

Например, на следующем рисунке изображены два удаленных подключения из вашего репозитория к центральному репозиторию и репозиторию другого разработчика. Вместо того, чтобы ссылаться на них по их полным URL-адресам, вы можете передавать командам Git только ярлыки origin и john.

How to change remote git. Смотреть фото How to change remote git. Смотреть картинку How to change remote git. Картинка про How to change remote git. Фото How to change remote git

Обзор использования git remote

По сути, команда git remote — это интерфейс для управления списком записей об удаленных подключениях, которые хранятся в файле /.git/config репозитория. Для просмотра текущего состояния списка удаленных подключений используются следующие команды.

Просмотр конфигураций удаленных репозиториев Git

Список ваших удаленных подключений к другим репозиториям.

Аналогично команде выше, но включает URL-адрес каждого подключения.

Создание и изменение конфигураций удаленных репозиториев Git

Команда git remote также предоставляет удобный способ изменения файла /.git/config репозитория. Перечисленные ниже команды позволяют управлять подключениями к другим репозиториям и изменять файл /.git/config репозитория. Такого же результата можно достичь, напрямую отредактировав файл /.git/config с помощью текстового редактора.

Создание нового подключения к удаленному репозиторию. После добавления удаленного репозитория имя <name> можно использовать в качестве удобного ярлыка для адреса <url> в других командах Git.

Обсуждение git remote

Git предоставляет каждому разработчику полностью изолированную среду разработки. Информация не передается между репозиториями автоматически. Вместо этого разработчикам нужно вручную загружать вышестоящие коммиты в локальный репозиторий или вручную отправлять локальные коммиты обратно в центральный репозиторий. Команда git remote представляет собой простой способ передачи URL-адресов в эти команды обмена.

Удаленное подключение к origin

В процессе клонирования с помощью команды git clone автоматически создается удаленное подключение к исходному репозиторию (такое соединение называется origin). Это позволяет разработчикам, создающим локальную копию центрального репозитория, легко загружать вышестоящие изменения или публиковать локальные коммиты. Именно поэтому большинство проектов на основе Git называют свой центральный репозиторий origin.

URL-адреса репозиториев

Git поддерживает различные способы ссылки на удаленный репозиторий. Два наиболее простых способа доступа к удаленному репозиторию: протоколы HTTP и SSH. Протокол HTTP — простой способ разрешить к репозиторию анонимный доступ только для чтения. Пример ниже.

Однако HTTP-адрес, как правило, не позволяет отправлять коммиты (в любом случае вы не захотите разрешать анонимную отправку изменений с помощью команды push). Чтобы использовать доступ для чтения и записи следует использовать протокол SSH:

Вам понадобится лишь действующий аккаунт SSH на хост-машине, а в остальном Git поддерживает аутентифицированный доступ через SSH по умолчанию. Необходимые URL-адреса предоставляются современными безопасными решениями для хостинга от сторонних провайдеров, например Bitbucket.com.

Команды git remote

Вывод URL-адресов для записи об удаленном репозитории.

Удаляет из репозитория <NAME> все локальные ветки, которые отсутствуют в удаленном репозитории.

Примеры git remote

Доступа к индивидуальным репозиториям разработчиков позволяет вести совместную работу за пределами центрального репозитория. Это может быть очень полезно для небольших команд, работающих над большим проектом.

Просмотр удаленных репозиториев

По умолчанию команда git remote отображает ранее сохраненные удаленные подключения к другим репозиториям. Создается однострочный список закладок с именами удаленных репозиториев.

Добавление удаленных репозиториев

Проверка удаленного репозитория

Для получения подробного вывода о конфигурации удаленного репозитория к команде git remote можно добавить подкоманду show. Вывод будет содержать список веток, связанных с удаленным репозиторием, а также конечных точек, подключенных для извлечения (fetch) и отправки (push).

Получение и извлечение данных из удаленных репозиториев Git

Отправка данных в удаленные репозитории Git

Переименование и удаление удаленных репозиториев

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *