Как изменить удаленный репозиторий гит

Learn to work with your local repositories on your computer and remote repositories hosted on GitHub.

Adding a remote repository

To add a new remote, use the git remote add command on the terminal, in the directory your repository is stored at.

The git remote add command takes two arguments:

  • A remote name, for example, origin
  • A remote URL, for example, https://github.com/user/repo.git

For example:

$ git remote add origin https://github.com/USER/REPO.git
# Set a new remote

$ git remote -v
# Verify new remote
> origin  https://github.com/USER/REPO.git (fetch)
> origin  https://github.com/USER/REPO.git (push)

For more information on which URL to use, see «About remote repositories.»

Troubleshooting: Remote origin already exists

This error means you’ve tried to add a remote with a name that already exists in your local repository.

$ git remote add origin https://github.com/octocat/Spoon-Knife.git
> fatal: remote origin already exists.

To fix this, you can:

  • Use a different name for the new remote.
  • Rename the existing remote repository before you add the new remote. For more information, see «Renaming a remote repository» below.
  • Delete the existing remote repository before you add the new remote. For more information, see «Removing a remote repository» below.

Changing a remote repository’s URL

The git remote set-url command changes an existing remote repository URL.

The git remote set-url command takes two arguments:

  • An existing remote name. For example, origin or upstream are two common choices.
  • A new URL for the remote. For example:
    • If you’re updating to use HTTPS, your URL might look like:
      https://github.com/USERNAME/REPOSITORY.git
    • If you’re updating to use SSH, your URL might look like:
      git@github.com:USERNAME/REPOSITORY.git

Switching remote URLs from SSH to HTTPS

  1. Open TerminalTerminalGit Bash.
  2. Change the current working directory to your local project.
  3. List your existing remotes in order to get the name of the remote you want to change.
    $ git remote -v
    > origin  git@github.com:USERNAME/REPOSITORY.git (fetch)
    > origin  git@github.com:USERNAME/REPOSITORY.git (push)
  4. Change your remote’s URL from SSH to HTTPS with the git remote set-url command.
    $ git remote set-url origin https://github.com/USERNAME/REPOSITORY.git
  5. Verify that the remote URL has changed.
    $ git remote -v
    # Verify new remote URL
    > origin  https://github.com/USERNAME/REPOSITORY.git (fetch)
    > origin  https://github.com/USERNAME/REPOSITORY.git (push)

The next time you git fetch, git pull, or git push to the remote repository, you’ll be asked for your GitHub username and password. When Git prompts you for your password, enter your personal access token. Alternatively, you can use a credential helper like Git Credential Manager. Password-based authentication for Git has been removed in favor of more secure authentication methods. For more information, see «Creating a personal access token.»

You can use a credential helper so Git will remember your GitHub username and personal access token every time it talks to GitHub.

Switching remote URLs from HTTPS to SSH

  1. Open TerminalTerminalGit Bash.
  2. Change the current working directory to your local project.
  3. List your existing remotes in order to get the name of the remote you want to change.
    $ git remote -v
    > origin  https://github.com/USERNAME/REPOSITORY.git (fetch)
    > origin  https://github.com/USERNAME/REPOSITORY.git (push)
  4. Change your remote’s URL from HTTPS to SSH with the git remote set-url command.
    $ git remote set-url origin git@github.com:USERNAME/REPOSITORY.git
  5. Verify that the remote URL has changed.
    $ git remote -v
    # Verify new remote URL
    > origin  git@github.com: USERNAME/REPOSITORY.git (fetch)
    > origin  git@github.com: USERNAME/REPOSITORY.git (push)

Troubleshooting: No such remote ‘[name]’

This error means that the remote you tried to change doesn’t exist:

$ git remote set-url sofake https://github.com/octocat/Spoon-Knife
> fatal: No such remote 'sofake'

Check that you’ve correctly typed the remote name.

Renaming a remote repository

Use the git remote rename command to rename an existing remote.

The git remote rename command takes two arguments:

  • An existing remote name, for example, origin
  • A new name for the remote, for example, destination

Example of renaming a remote repository

These examples assume you’re cloning using HTTPS, which is recommended.

$ git remote -v
# View existing remotes
> origin  https://github.com/OWNER/REPOSITORY.git (fetch)
> origin  https://github.com/OWNER/REPOSITORY.git (push)

$ git remote rename origin destination
# Change remote name from 'origin' to 'destination'

$ git remote -v
# Verify remote's new name
> destination  https://github.com/OWNER/REPOSITORY.git (fetch)
> destination  https://github.com/OWNER/REPOSITORY.git (push)

Troubleshooting: Could not rename config section ‘remote.[old name]’ to ‘remote.[new name]’

This error means that the old remote name you typed doesn’t exist.

You can check which remotes currently exist with the git remote -v command:

$ git remote -v
# View existing remotes
> origin  https://github.com/OWNER/REPOSITORY.git (fetch)
> origin  https://github.com/OWNER/REPOSITORY.git (push)

Troubleshooting: Remote [new name] already exists

This error means that the remote name you want to use already exists. To solve this, either use a different remote name, or rename the original remote.

Removing a remote repository

Use the git remote rm command to remove a remote URL from your repository.

The git remote rm command takes one argument:

  • A remote name, for example, destination

Removing the remote URL from your repository only unlinks the local and remote repositories. It does not delete the remote repository.

Example of removing a remote repository

These examples assume you’re cloning using HTTPS, which is recommended.

$ git remote -v
# View current remotes
> origin  https://github.com/OWNER/REPOSITORY.git (fetch)
> origin  https://github.com/OWNER/REPOSITORY.git (push)
> destination  https://github.com/FORKER/REPOSITORY.git (fetch)
> destination  https://github.com/FORKER/REPOSITORY.git (push)

$ git remote rm destination
# Remove remote
$ git remote -v
# Verify it's gone
> origin  https://github.com/OWNER/REPOSITORY.git (fetch)
> origin  https://github.com/OWNER/REPOSITORY.git (push)

Note: git remote rm does not delete the remote repository from the server. It simply
removes the remote and its references from your local repository.

Troubleshooting: Could not remove config section ‘remote.[name]’

This error means that the remote you tried to delete doesn’t exist:

$ git remote rm sofake
> error: Could not remove config section 'remote.sofake'

Check that you’ve correctly typed the remote name.

Further reading

  • «Working with Remotes» from the Pro Git book

Работа с удалёнными репозиториями

Для того, чтобы внести вклад в какой-либо Git-проект, вам необходимо уметь работать с удалёнными репозиториями.
Удалённые репозитории представляют собой версии вашего проекта, сохранённые в интернете или ещё где-то в сети.
У вас может быть несколько удалённых репозиториев, каждый из которых может быть доступен для чтения или для чтения-записи.
Взаимодействие с другими пользователями предполагает управление удалёнными репозиториями, а также отправку и получение данных из них.
Управление репозиториями включает в себя как умение добавлять новые, так и умение удалять устаревшие репозитории, а также умение управлять различными удалёнными ветками, объявлять их отслеживаемыми или нет и так далее.
В данном разделе мы рассмотрим некоторые из этих навыков.

Примечание

Удаленный репозиторий может находиться на вашем локальном компьютере.

Вполне возможно, что удалённый репозиторий будет находиться на том же компьютере, на котором работаете вы.
Слово «удалённый» не означает, что репозиторий обязательно должен быть где-то в сети или Интернет, а значит только — где-то ещё.
Работа с таким удалённым репозиторием подразумевает выполнение стандартных операций отправки и получения, как и с любым другим удалённым репозиторием.

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

Для того, чтобы просмотреть список настроенных удалённых репозиториев, вы можете запустить команду git remote.
Она выведет названия доступных удалённых репозиториев.
Если вы клонировали репозиторий, то увидите как минимум origin — имя по умолчанию, которое Git даёт серверу, с которого производилось клонирование:

$ git clone https://github.com/schacon/ticgit
Cloning into 'ticgit'...
remote: Reusing existing pack: 1857, done.
remote: Total 1857 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (1857/1857), 374.35 KiB | 268.00 KiB/s, done.
Resolving deltas: 100% (772/772), done.
Checking connectivity... done.
$ cd ticgit
$ git remote
origin

Вы можете также указать ключ -v, чтобы просмотреть адреса для чтения и записи, привязанные к репозиторию:

$ git remote -v
origin	https://github.com/schacon/ticgit (fetch)
origin	https://github.com/schacon/ticgit (push)

Если у вас больше одного удалённого репозитория, команда выведет их все.
Например, для репозитория с несколькими настроенными удалёнными репозиториями в случае совместной работы нескольких пользователей, вывод команды может выглядеть примерно так:

$ cd grit
$ git remote -v
bakkdoor  https://github.com/bakkdoor/grit (fetch)
bakkdoor  https://github.com/bakkdoor/grit (push)
cho45     https://github.com/cho45/grit (fetch)
cho45     https://github.com/cho45/grit (push)
defunkt   https://github.com/defunkt/grit (fetch)
defunkt   https://github.com/defunkt/grit (push)
koke      git://github.com/koke/grit.git (fetch)
koke      git://github.com/koke/grit.git (push)
origin    git@github.com:mojombo/grit.git (fetch)
origin    git@github.com:mojombo/grit.git (push)

Это означает, что мы можем легко получить изменения от любого из этих пользователей.
Возможно, что некоторые из репозиториев доступны для записи и в них можно отправлять свои изменения, хотя вывод команды не даёт никакой информации о правах доступа.

Обратите внимание на разнообразие протоколов, используемых при указании адреса удалённого репозитория; подробнее мы рассмотрим протоколы в разделе Установка Git на сервер главы 4.

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

В предыдущих разделах мы уже упоминали и приводили примеры добавления удалённых репозиториев, сейчас рассмотрим эту операцию подробнее.
Для того, чтобы добавить удалённый репозиторий и присвоить ему имя (shortname), просто выполните команду git remote add <shortname> <url>:

$ git remote
origin
$ git remote add pb https://github.com/paulboone/ticgit
$ git remote -v
origin	https://github.com/schacon/ticgit (fetch)
origin	https://github.com/schacon/ticgit (push)
pb	https://github.com/paulboone/ticgit (fetch)
pb	https://github.com/paulboone/ticgit (push)

Теперь вместо указания полного пути вы можете использовать pb.
Например, если вы хотите получить изменения, которые есть у Пола, но нету у вас, вы можете выполнить команду git fetch pb:

$ git fetch pb
remote: Counting objects: 43, done.
remote: Compressing objects: 100% (36/36), done.
remote: Total 43 (delta 10), reused 31 (delta 5)
Unpacking objects: 100% (43/43), done.
From https://github.com/paulboone/ticgit
 * [new branch]      master     -> pb/master
 * [new branch]      ticgit     -> pb/ticgit

Ветка master из репозитория Пола сейчас доступна вам под именем pb/master.
Вы можете слить её с одной из ваших веток или переключить на неё локальную ветку, чтобы просмотреть содержимое ветки Пола.
Более подробно работа с ветками рассмотрена в главе Ветвление в Git.

Получение изменений из удалённого репозитория — Fetch и Pull

Как вы только что узнали, для получения данных из удалённых проектов, следует выполнить:

$ git fetch [remote-name]

Данная команда связывается с указанным удалённым проектом и забирает все те данные проекта, которых у вас ещё нет.
После того как вы выполнили команду, у вас должны появиться ссылки на все ветки из этого удалённого проекта, которые вы можете просмотреть или слить в любой момент.

Когда вы клонируете репозиторий, команда clone автоматически добавляет этот удалённый репозиторий под именем «origin».
Таким образом, git fetch origin извлекает все наработки, отправленные на этот сервер после того, как вы его клонировали (или получили изменения с помощью fetch).
Важно отметить, что команда git fetch забирает данные в ваш локальный репозиторий, но не сливает их с какими-либо вашими наработками и не модифицирует то, над чем вы работаете в данный момент.
Вам необходимо вручную слить эти данные с вашими, когда вы будете готовы.

Если ветка настроена на отслеживание удалённой ветки (см. следующий раздел и главу Ветвление в Git чтобы получить больше информации), то вы можете использовать команду git pull чтобы автоматически получить изменения из удалённой ветки и слить их со своей текущей.
Этот способ может для вас оказаться более простым или более удобным.
К тому же, по умолчанию команда git clone автоматически настраивает вашу локальную ветку master на отслеживание удалённой ветки master на сервере, с которого вы клонировали репозиторий.
Название веток может быть другим и зависит от ветки по умолчанию на сервере.
Выполнение git pull, как правило, извлекает (fetch) данные с сервера, с которого вы изначально клонировали, и автоматически пытается слить (merge) их с кодом, над которым вы в данный момент работаете.

Примечание

Начиная с версии 2.27, команда git pull выдаёт предупреждение, если настройка pull.rebase не установлена.
Git будет выводить это предупреждение каждый раз пока настройка не будет установлена.

Если хотите использовать поведение Git по умолчанию (простое смещение вперёд если возможно — иначе создание коммита слияния):
git config --global pull.rebase "false"

Если хотите использовать перебазирование при получении изменений:
git config --global pull.rebase "true"

Отправка изменений в удаленный репозиторий (Push)

Когда вы хотите поделиться своими наработками, вам необходимо отправить их в удалённый репозиторий.
Команда для этого действия простая: git push <remote-name> <branch-name>.
Чтобы отправить вашу ветку master на сервер origin (повторимся, что клонирование обычно настраивает оба этих имени автоматически), вы можете выполнить следующую команду для отправки ваших коммитов:

Эта команда срабатывает только в случае, если вы клонировали с сервера, на котором у вас есть права на запись, и если никто другой с тех пор не выполнял команду push.
Если вы и кто-то ещё одновременно клонируете, затем он выполняет команду push, а после него выполнить команду push попытаетесь вы, то ваш push точно будет отклонён.
Вам придётся сначала получить изменения и объединить их с вашими и только после этого вам будет позволено выполнить push.
Обратитесь к главе Ветвление в Git для более подробного описания, как отправлять изменения на удалённый сервер.

Просмотр удаленного репозитория

Если хотите получить побольше информации об одном из удалённых репозиториев, вы можете использовать команду git remote show <remote>.
Выполнив эту команду с некоторым именем, например, origin, вы получите следующий результат:

$ git remote show origin
* remote origin
  Fetch URL: https://github.com/schacon/ticgit
  Push  URL: https://github.com/schacon/ticgit
  HEAD branch: master
  Remote branches:
    master                               tracked
    dev-branch                           tracked
  Local branch configured for 'git pull':
    master merges with remote master
  Local ref configured for 'git push':
    master pushes to master (up to date)

Она выдаёт URL удалённого репозитория, а также информацию об отслеживаемых ветках.
Эта команда любезно сообщает вам, что если вы, находясь на ветке master, выполните git pull, ветка master с удалённого сервера будет автоматически влита в вашу сразу после получения всех необходимых данных.
Она также выдаёт список всех полученных ею ссылок.

Это был пример для простой ситуации и вы наверняка встречались с чем-то подобным.
Однако, если вы используете Git более интенсивно, вы можете увидеть гораздо большее количество информации от git remote show:

$ git remote show origin
* remote origin
  URL: https://github.com/my-org/complex-project
  Fetch URL: https://github.com/my-org/complex-project
  Push  URL: https://github.com/my-org/complex-project
  HEAD branch: master
  Remote branches:
    master                           tracked
    dev-branch                       tracked
    markdown-strip                   tracked
    issue-43                         new (next fetch will store in remotes/origin)
    issue-45                         new (next fetch will store in remotes/origin)
    refs/remotes/origin/issue-11     stale (use 'git remote prune' to remove)
  Local branches configured for 'git pull':
    dev-branch merges with remote dev-branch
    master     merges with remote master
  Local refs configured for 'git push':
    dev-branch                     pushes to dev-branch                     (up to date)
    markdown-strip                 pushes to markdown-strip                 (up to date)
    master                         pushes to master                         (up to date)

Данная команда показывает какая именно локальная ветка будет отправлена на удалённый сервер по умолчанию при выполнении git push.
Она также показывает, каких веток с удалённого сервера у вас ещё нет, какие ветки всё ещё есть у вас, но уже удалены на сервере, и для нескольких веток показано, какие удалённые ветки будут в них влиты при выполнении git pull.

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

Для переименования удалённого репозитория можно выполнить git remote rename.
Например, если вы хотите переименовать pb в paul, вы можете это сделать при помощи git remote rename:

$ git remote rename pb paul
$ git remote
origin
paul

Стоит упомянуть, что это также изменит имена удалённых веток в вашем репозитории.
То, к чему вы обращались как pb/master, теперь стало paul/master.

Если по какой-то причине вы хотите удалить удаленный репозиторий — вы сменили сервер или больше не используете определённое зеркало, или кто-то перестал вносить изменения — вы можете использовать git remote rm:

$ git remote remove paul
$ git remote
origin

При удалении ссылки на удалённый репозиторий все отслеживаемые ветки и настройки, связанные с этим репозиторием, так же будут удалены.

You can

git remote set-url origin new.git.url/here

See git help remote. You also can edit .git/config and change the URLs there.

You’re not in any danger of losing history unless you do something very silly (and if you’re worried, just make a copy of your repo, since your repo is your history.)

Matthias Braun's user avatar

answered Mar 12, 2010 at 12:55

hobbs's user avatar

hobbshobbs

217k18 gold badges206 silver badges286 bronze badges

20

git remote -v
# View existing remotes
# origin  https://github.com/user/repo.git (fetch)
# origin  https://github.com/user/repo.git (push)

git remote set-url origin https://github.com/user/repo2.git
# Change the 'origin' remote's URL

git remote -v
# Verify new remote URL
# origin  https://github.com/user/repo2.git (fetch)
# origin  https://github.com/user/repo2.git (push)

Changing a remote’s URL

Zombo's user avatar

answered Oct 10, 2013 at 14:43

Utensil's user avatar

UtensilUtensil

16.3k1 gold badge16 silver badges10 bronze badges

4

git remote set-url {name} {url}

git remote set-url origin https://github.com/myName/GitTest.git

Thavas Antonio's user avatar

answered Dec 28, 2015 at 4:53

최봉재's user avatar

최봉재최봉재

3,9433 gold badges16 silver badges21 bronze badges

1

Change Host for a Git Origin Server

from: http://pseudofish.com/blog/2010/06/28/change-host-for-a-git-origin-server/

Hopefully this isn’t something you need to do. The server that I’ve been using to collaborate on a few git projects with had the domain name expire. This meant finding a way of migrating the local repositories to get back in sync.

Update: Thanks to @mawolf for pointing out there is an easy way with recent git versions (post Feb, 2010):

git remote set-url origin ssh://newhost.com/usr/local/gitroot/myproject.git

See the man page for details.

If you’re on an older version, then try this:

As a caveat, this works only as it is the same server, just with different names.

Assuming that the new hostname is newhost.com, and the old one was oldhost.com, the change is quite simple.

Edit the .git/config file in your working directory. You should see something like:

[remote "origin"]
fetch = +refs/heads/*:refs/remotes/origin/*
url = ssh://oldhost.com/usr/local/gitroot/myproject.git

Change oldhost.com to newhost.com, save the file and you’re done.

From my limited testing (git pull origin; git push origin; gitx) everything seems in order. And yes, I know it is bad form to mess with git internals.

Craig McQueen's user avatar

Craig McQueen

40.9k28 gold badges126 silver badges179 bronze badges

answered Feb 15, 2011 at 2:52

yoda's user avatar

yodayoda

4,7593 gold badges19 silver badges9 bronze badges

2

This is very easy and simple; just follow these instructions.

  1. For adding or changing the remote origin:
    git remote set-url origin githubrepurl
    
  2. To see which remote URL you have currently in this local repository:
    git remote show origin
    

Matthias Braun's user avatar

answered Feb 1, 2022 at 21:33

Mithun Rana's user avatar

Mithun RanaMithun Rana

1,2261 gold badge7 silver badges10 bronze badges

1

Switching remote URLs

Open Terminal.

Ist Step:— Change the current working directory to your local project.

2nd Step:— List your existing remotes in order to get the name of the remote you want to change.

git remote -v

origin  https://github.com/USERNAME/REPOSITORY.git (fetch)

origin  https://github.com/USERNAME/REPOSITORY.git (push)

Change your remote’s URL from HTTPS to SSH with the git remote set-url command.

3rd Step:git remote set-url origin git@github.com:USERNAME/REPOSITORY.git

4th Step:— Now Verify that the remote URL has changed.

git remote -v
Verify new remote URL

origin  git@github.com:USERNAME/REPOSITORY.git (fetch)
origin  git@github.com:USERNAME/REPOSITORY.git (push)

Community's user avatar

answered Dec 8, 2017 at 11:01

VIKAS KOHLI's user avatar

VIKAS KOHLIVIKAS KOHLI

7,8763 gold badges49 silver badges57 bronze badges

2

git remote set-url origin git://new.location

(alternatively, open .git/config, look for [remote "origin"], and edit the url = line.

You can check it worked by examining the remotes:

git remote -v
# origin  git://new.location (fetch)
# origin  git://new.location (push)

Next time you push, you’ll have to specify the new upstream branch, e.g.:

git push -u origin master

See also: GitHub: Changing a remote’s URL

answered Apr 26, 2015 at 23:13

Zaz's user avatar

ZazZaz

45.5k11 gold badges82 silver badges97 bronze badges

2

As seen here,

$ git remote rm origin
$ git remote add origin git@github.com:aplikacjainfo/proj1.git
$ git config master.remote origin
$ git config master.merge refs/heads/master

trashgod's user avatar

trashgod

203k29 gold badges242 silver badges1028 bronze badges

answered Apr 2, 2020 at 8:24

Zahid Hassan Shaikot's user avatar

3

  1. remove origin using command on gitbash
    git remote rm origin
  2. And now add new Origin using gitbash
    git remote add origin (Copy HTTP URL from your project repository in bit bucket)
    done

answered Jun 24, 2016 at 11:10

Sunil Chaudhary's user avatar

3

First you need to type this command to view existing remotes

git remote -v

Then second you need to type this command to Change the ‘origin’ remote’s URL

git remote set-url origin <paste your GitHub URL>

arnavakhoury's user avatar

answered May 1, 2022 at 23:05

Abdullah Al Mahmud's user avatar

Write the below command from your repo terminal:

git remote set-url origin git@github.com:<username>/<repo>.git

Refer this link for more details about changing the url in the remote.

answered Dec 19, 2019 at 9:25

viveknaskar's user avatar

viveknaskarviveknaskar

2,0161 gold badge19 silver badges34 bronze badges

0

To check git remote connection:

git remote -v

Now, set the local repository to remote git:

git remote set-url origin https://NewRepoLink.git

Now to make it upstream or push use following code:

git push --set-upstream origin master -f

answered Dec 18, 2018 at 5:22

Anupam Maurya's user avatar

1

Navigate to the project root of the local repository and check for existing remotes:

git remote -v

If your repository is using SSH you will see something like:

> origin  git@github.com:USERNAME/REPOSITORY.git (fetch)
> origin  git@github.com:USERNAME/REPOSITORY.git (push)

And if your repository is using HTTPS you will see something like:

> origin  https://github.com/USERNAME/REPOSITORY.git (fetch)
> origin  https://github.com/USERNAME/REPOSITORY.git (push)

Changing the URL is done with git remote set-url. Depending on the output of git remote -v, you can change the URL in the following manner:

In case of SSH, you can change the URL from REPOSITORY.git to NEW_REPOSITORY.git like:

$ git remote set-url origin git@github.com:USERNAME/NEW_REPOSITORY.git

And in case of HTTPS, you can change the URL from REPOSITORY.git to NEW_REPOSITORY.git like:

$ git remote set-url origin https://github.com/USERNAME/NEW_REPOSITORY.git

NOTE: If you’ve changed your GitHub username, you can follow the same process as above to update the change in the username associated with your repository. You would only have to update the USERNAME in the git remote set-url command.

answered Aug 17, 2020 at 20:03

Saurabh's user avatar

SaurabhSaurabh

4,0962 gold badges28 silver badges39 bronze badges

if you cloned your local will automatically consist,

remote URL where it gets cloned.

you can check it using git remote -v

if you want to made change in it,

git remote set-url origin https://github.io/my_repo.git

here,

origin — your branch

if you want to overwrite existing branch you can still use it.. it will override your existing … it will do,

git remote remove url
and 
git remote add origin url

for you…

answered Jul 31, 2017 at 7:33

Mohideen bin Mohammed's user avatar

1

I worked:

git remote set-url origin <project>

answered May 6, 2018 at 18:24

Diego Santa Cruz Mendezú's user avatar

In the Git Bash, enter the command:

git remote set-url origin https://NewRepoLink.git

Enter the Credentials

Done

answered Apr 25, 2017 at 9:48

devDeejay's user avatar

devDeejaydevDeejay

5,3551 gold badge26 silver badges38 bronze badges

You have a lot of ways to do that:

Console

git remote set-url origin [Here new url] 

Just be sure that you’ve opened it in a place where a repository is.

Config

It is placed in .git/config (same folder as repository)

[core]
    repositoryformatversion = 0
    filemode = false
    bare = false
    logallrefupdates = true
    symlinks = false
    ignorecase = true
[remote "origin"]
    url = [Here new url]  <------------------------------------
...

TortoiseGit

Step 1 - open settings

Step 2 - change url

Then just edit URL.

SourceTree

  1. Click on the «Settings» button on the toolbar to open the Repository Settings window.

  2. Click «Add» to add a remote repository path to the repository. A «Remote details» window will open.

  3. Enter a name for the remote path.

  4. Enter the URL/Path for the remote repository

  5. Enter the username for the hosting service for the remote repository.

  6. Click ‘OK’ to add the remote path.

  7. Back on the Repository Settings window, click ‘OK’. The new remote path should be added on the repository now.

  8. If you need to edit an already added remote path, just click the ‘Edit’ button. You should be directed to the «Remote details» window where you can edit the details (URL/Path/Host Type) of the remote path.

  9. To remove a remote repository path, click the ‘Remove’ button

enter image description here

enter image description here

ref. Support

answered Apr 2, 2019 at 13:37

Przemek Struciński's user avatar

For me, the accepted answer worked only in the case of fetch but not pull. I did the following to make it work for push as well.

git remote set-url --push origin new.git.url/here

So to update the fetch URL:

git remote set-url origin new.git.url/here

To update the pull URL:

git remote set-url --push origin new.git.url/here

answered May 6, 2021 at 11:27

Shailendra Madda's user avatar

Shailendra MaddaShailendra Madda

20.1k15 gold badges95 silver badges137 bronze badges

Change remote git URI to git@github.com rather than https://github.com

git remote set-url origin git@github.com:<username>/<repo>.git

Example:

git remote set-url origin git@github.com:Chetabahana/my_repo_name.git

The benefit is that you may do git push automatically when you use ssh-agent :

#!/bin/bash

# Check ssh connection
ssh-add -l &>/dev/null
[[ "$?" == 2 ]] && eval `ssh-agent`
ssh-add -l &>/dev/null
[[ "$?" == 1 ]] && expect $HOME/.ssh/agent

# Send git commands to push
git add . && git commit -m "your commit" && git push -u origin master

Put a script file $HOME/.ssh/agent to let it runs ssh-add using expect as below:

#!/usr/bin/expect -f
set HOME $env(HOME)
spawn ssh-add $HOME/.ssh/id_rsa
expect "Enter passphrase for $HOME/.ssh/id_rsa:"
send "<my_passphrase>n";
expect "Identity added: $HOME/.ssh/id_rsa ($HOME/.ssh/id_rsa)"
interact

BenKoshy's user avatar

BenKoshy

32k14 gold badges103 silver badges78 bronze badges

answered May 25, 2019 at 11:54

eQ19's user avatar

eQ19eQ19

9,5303 gold badges62 silver badges76 bronze badges

To change the remote upstream:
git remote set-url origin <url>


To add more upstreams:
git remote add newplace <url>

So you can choose where to work
git push origin <branch> or git push newplace <branch>

answered Feb 28, 2020 at 13:43

Anderson Cossul's user avatar

0

You can change the url by editing the config file.
Go to your project root:

nano .git/config

Then edit the url field and set your new url.
Save the changes. You can verify the changes by using the command.

git remote -v 

answered Feb 7, 2020 at 4:24

Abhi Das's user avatar

Abhi DasAbhi Das

50110 silver badges11 bronze badges

An alternative approach is to rename the ‘old’ origin (in the example below I name it simply old-origin) and adding a new one. This might be the desired approach if you still want to be able to push to the old origin every now and then:

git remote rename origin old-origin
git remote add origin git@new-git-server.com>:<username>/<projectname>.git

And in case you need to push your local state to the new origin:

git push -u origin --all
git push -u origin --tags

answered Sep 20, 2020 at 12:25

j-i-l's user avatar

j-i-lj-i-l

9,7862 gold badges49 silver badges69 bronze badges

If you’re using TortoiseGit then follow the below steps:

  1. Go to your local checkout folder and right click to go to TortoiseGit -> Settings
  2. In the left pane choose Git -> Remote
  3. In the right pane choose origin
  4. Now change the URL text box value to where ever your new remote repository is

Your branch and all your local commits will remain intact and you can keep working as you were before.

Don't Panic's user avatar

Don’t Panic

40.8k10 gold badges61 silver badges78 bronze badges

answered Aug 20, 2017 at 15:14

Vipul bhojwani's user avatar

0

It will work fine, you can try this

For SSH:

command: git remote set-url origin <ssh_url>

example: git remote set-url origin git@github.com:username/rep_name.git

For HTTPS:

command: git remote set-url origin <https_url>

example: git remote set-url origin https://github.com/username/REPOSITORY.git

answered Dec 26, 2022 at 7:51

MD. SHIFULLAH's user avatar

Removing a remote

Use the git remote rm command to remove a remote URL from your repository.

    $ git remote -v
    # View current remotes
    > origin  https://github.com/OWNER/REPOSITORY.git (fetch)
    > origin  https://github.com/OWNER/REPOSITORY.git (push)
    > destination  https://github.com/FORKER/REPOSITORY.git (fetch)
    > destination  https://github.com/FORKER/REPOSITORY.git (push)

    $ git remote rm destination
    # Remove remote
    $ git remote -v
    # Verify it's gone
    > origin  https://github.com/OWNER/REPOSITORY.git (fetch)
    > origin  https://github.com/OWNER/REPOSITORY.git (push)

answered Jun 6, 2020 at 11:05

Tayyab Roy's user avatar

Tayyab RoyTayyab Roy

4235 silver badges7 bronze badges

If you would like to set the username and password as well in the origin url, you can follow the below steps.

Exporting the password in a variable would avoid issues with special characters.

Steps:

export gituser='<Username>:<password>@'
git remote set-url origin https://${gituser}<gitlab_repo_url> 
git push origin <Branch Name>

answered Mar 3, 2021 at 5:52

Rajesh Somasundaram's user avatar

check your privilege

in my case i need to check my username

i have two or three repository with seperate credentials.

problem is my permission i have two private git server and repositories

this second account is admin of that new repo and first one is my default user account and i should grant permission to first

answered Feb 6, 2020 at 16:35

saber tabatabaee yazdi's user avatar

(Only Windows PS) To change a server/protocol recursively in all local repos

Get-ChildItem -Directory -Recurse -Depth [Number] -Hidden -name | %{$_.replace(".git","")} | %{git -C $_ remote set-url origin $(git -C $_ remote get-url origin).replace("[OLD SERVER]", "[NEW SERVER]")}

answered May 17, 2021 at 10:05

bruegth's user avatar

bruegthbruegth

3583 silver badges12 bronze badges

For those who want to make this change from Visual Studio 2019

Open Team Explorer (Ctrl+M)

Home -> Settings

Git -> Repository Settings

Remotes -> Edit

enter image description here

answered Oct 25, 2019 at 17:53

Dinch's user avatar

DinchDinch

5284 silver badges9 bronze badges

Продолжаю изучение темы Git и GitHub. На повестке дня стоит вопрос — каким образом можно изменить ссылку существующего репозитория?

Нет — не так! Попробую зайти с другой стороны и сказать иначе. Имеется готовый репозиторий Template, размещенный на сервере GitHub. Этот репозиторий является шаблоном (template starter) при создании разнообразных проектов. Нечто похожим на известный HTML5 Boilerplate.

Репозиторий Template клонируется на локальную машину с именем разрабатываемого проекта, такой командой:

$ git clone https://github.com/gearmobile/template.git project

Затем в созданном репозитории Project разрабатывается требуемый проект.

Но есть одно НО — необходимо преобразовать видоизмененный репозиторий Project в отдельный, самостоятельный репозиторий. Конечно, по большому счету, это уже и есть отдельный, самостоятельный репозиторий.

Но вот ссылка у репозитория Project указывает на оригинал — репозиторий Template. И если произвести

на GitHub, то произойдет обновление репозитория Template.

А этого крайне нежелательно допустить, так как этот репозиторий является стартовым, чистым листом для всех новых проектов!

У меня же стоит такая задача — скопировать стартовый репозиторий Template на локальную машину, преобразовать его в конкретный проект, вновь залить на GitHub уже как самостоятельный репозиторий с именем проекта в качестве имени репозитория. Как поступить?

Можно решить вопрос несколькими способами. Ниже приведу пару из них — самых простых и доступных для моего понимания вечного newbie в GitGitHub. Может быть, по мере освоения темы дополню статью более универсальным и грамотным способом.

Правка config

У клонированного на локальную машину репозитория ссылка на его удаленный оригинал размещена в конфигурационном файле

по пути

1
.git/config

, в секции

1
[remote "origin"]

, в переменной с именем

1
url

:

$ cat .git/config

[core]
  repositoryformatversion = 0
  filemode = true
  bare = false
  logallrefupdates = true
  ignorecase = true
  precomposeunicode = true

[remote "origin"]
  url = https://github.com/gearmobile/template.git
  fetch = +refs/heads/*:refs/remotes/origin/*

[branch "master"]
  remote = origin
  merge = refs/heads/master

Поэтому в локальном репозитории Project можно просто изменить эту ссылку с помощью любого текстового редактора.

Отредактирую файл

и изменю в нем ссылку с

https://github.com/gearmobile/template.git

на

https://github.com/gearmobile/project.git

… где последняя — это ссылка на новый пустой репозиторий Project, который я создал на GitHub.

Теперь конфигурационный файл

для локального репозитория Project будет выглядеть таким образом (обратить внимание на переменную

1
url

):

$ cat .git/config

[core]
  repositoryformatversion = 0
  filemode = true
  bare = false
  logallrefupdates = true
  ignorecase = true
  precomposeunicode = true

[remote "origin"]
  url = https://github.com/gearmobile/project.git
  fetch = +refs/heads/*:refs/remotes/origin/*

[branch "master"]
  remote = origin
  merge = refs/heads/master

Все — теперь локальный репозиторий Project является абсолютно самостоятельным и уникальным репозиторием, связанным ссылкой со своей удаленной копией на сервере GitHub.

Осталось только сделать

, чтобы залить на GitHub. Правда, здесь придется воспользоваться ключом

1
-f

(как это описано в предыдущей статье Откат коммитов на GitHub):

$ git push -f

Команда set-url

Второй способ практически идентичен предыдущему за тем лишь исключением, что он более правильный, так как для изменения url-адреса репозитория используется предназначенная для этого консольная команда Git —

.

Точно также создаю на локальной машине копию Another Project удаленного репозитория Template:

$ git clone https://github.com/gearmobile/template.git another-project

Ссылка в новом репозитории Another-Project все также указывает на свой оригинал — репозиторий Template:

$ cat .git/config

[core]
  repositoryformatversion = 0
  filemode = true
  bare = false
  logallrefupdates = true
  ignorecase = true
  precomposeunicode = true

[remote "origin"]
  url = https://github.com/gearmobile/template.git
  fetch = +refs/heads/*:refs/remotes/origin/*

[branch "master"]
  remote = origin
  merge = refs/heads/master

Создаю на GitHub новый репозиторий Another-Project, который будет удаленной копией локального (уже существующего) репозитория Another-Project. И изменяю ссылку на вновь созданный удаленный репозиторий Another-Project:

$ git remote set-url origin https://github.com/gearmobile/another-project.git

Проверяю, изменилась ли ссылка в конфигурационном файле

(переменная

1
url

):

$ cat .git/config

[core]
  repositoryformatversion = 0
  filemode = true
  bare = false
  logallrefupdates = true
  ignorecase = true
  precomposeunicode = true

[remote "origin"]
  url = https://github.com/gearmobile/another-project.git
  fetch = +refs/heads/*:refs/remotes/origin/*

[branch "master"]
  remote = origin
  merge = refs/heads/master

Да, ссылка была успешно изменена на новый удаленный репозиторий Another-Project. Можно вносить изменения и выполнять

на GitHub.

Небольшое заключение

Преимущество двух описанных выше способ в том, что не теряется история коммитов.

На этом пока все.


I’ve recently cloned a repo to my local drive, but now I’m trying to push all changes to a complete new repo. However, git keeps telling me that permission is denied, and that’s because it’s trying to push to the originally-cloned repo.

DETAILS:

I originally cloned from https://github.com/taylonr/intro-to-protractor (i.e. based on a Pluralsight course at https://app.pluralsight.com/library/courses/protractor-introduction/table-of-contents ) .

Now that I’ve completed the course, I’d like to push my finalized code up to my own git repo (which I just created on github):

https://github.com/robertmazzo/intro-to-protractor

When I use the following git command:

git remote add origin https://github.com/robertmazzo/intro-to-protractor.git

it tells me remote origin already exists , which I guess is fine because I already created it on github.com.

However, when I push my changes up I’m getting an exception.

git push origin master

remote: Permission to taylonr/intro-to-protractor.git denied to robertmazzo.
fatal: unable to access 'https://github.com/taylonr/intro-to-protractor.git/':
The requested URL returned error: 403

So I’m investigating how I can switch to my new repository, but this is exactly where my issue is. I cannot figure this part out.

user229044's user avatar

user229044

229k40 gold badges329 silver badges336 bronze badges

asked Sep 6, 2016 at 14:31

bob.mazzo's user avatar

1

Before you can add a new remote named «origin», you need to either delete the old one, or simply rename it if you still need access to it for some reason.

# Pick one
git remote remove origin            # delete it, or ...
git remote rename origin old-origin # ... rename it

# Now you can add the new one
git remote add origin https://github.com/robertmazzo/intro-to-protractor.git

answered Sep 6, 2016 at 14:34

chepner's user avatar

chepnerchepner

479k70 gold badges502 silver badges653 bronze badges

origin is only an alias to identify your remote repository.

You can create a new remote reference and push

git remote add new_origin https://github.com/robertmazzo/intro-to-protractor.git
git push new_origin master

If you want to remove the previous reference

git remote remove origin

answered Sep 6, 2016 at 14:34

lubilis's user avatar

lubilislubilis

3,8424 gold badges32 silver badges54 bronze badges

Either add a new remote

git remote add <name> <url>

or, if you completely want to remove the old origin, first do

git remote remove origin

and then

git remote add origin <url>

Note that the message remote origin already exists is not fine. It tells you that the operation failed, i.e. it could not set the new remote.

answered Sep 6, 2016 at 14:33

Martin Nyolt's user avatar

Martin NyoltMartin Nyolt

4,3043 gold badges26 silver badges35 bronze badges

I’ve recently cloned a repo to my local drive, but now I’m trying to push all changes to a complete new repo. However, git keeps telling me that permission is denied, and that’s because it’s trying to push to the originally-cloned repo.

DETAILS:

I originally cloned from https://github.com/taylonr/intro-to-protractor (i.e. based on a Pluralsight course at https://app.pluralsight.com/library/courses/protractor-introduction/table-of-contents ) .

Now that I’ve completed the course, I’d like to push my finalized code up to my own git repo (which I just created on github):

https://github.com/robertmazzo/intro-to-protractor

When I use the following git command:

git remote add origin https://github.com/robertmazzo/intro-to-protractor.git

it tells me remote origin already exists , which I guess is fine because I already created it on github.com.

However, when I push my changes up I’m getting an exception.

git push origin master

remote: Permission to taylonr/intro-to-protractor.git denied to robertmazzo.
fatal: unable to access 'https://github.com/taylonr/intro-to-protractor.git/':
The requested URL returned error: 403

So I’m investigating how I can switch to my new repository, but this is exactly where my issue is. I cannot figure this part out.

user229044's user avatar

user229044

229k40 gold badges329 silver badges336 bronze badges

asked Sep 6, 2016 at 14:31

bob.mazzo's user avatar

1

Before you can add a new remote named «origin», you need to either delete the old one, or simply rename it if you still need access to it for some reason.

# Pick one
git remote remove origin            # delete it, or ...
git remote rename origin old-origin # ... rename it

# Now you can add the new one
git remote add origin https://github.com/robertmazzo/intro-to-protractor.git

answered Sep 6, 2016 at 14:34

chepner's user avatar

chepnerchepner

479k70 gold badges502 silver badges653 bronze badges

origin is only an alias to identify your remote repository.

You can create a new remote reference and push

git remote add new_origin https://github.com/robertmazzo/intro-to-protractor.git
git push new_origin master

If you want to remove the previous reference

git remote remove origin

answered Sep 6, 2016 at 14:34

lubilis's user avatar

lubilislubilis

3,8424 gold badges32 silver badges54 bronze badges

Either add a new remote

git remote add <name> <url>

or, if you completely want to remove the old origin, first do

git remote remove origin

and then

git remote add origin <url>

Note that the message remote origin already exists is not fine. It tells you that the operation failed, i.e. it could not set the new remote.

answered Sep 6, 2016 at 14:33

Martin Nyolt's user avatar

Martin NyoltMartin Nyolt

4,3043 gold badges26 silver badges35 bronze badges

Git remote — это указатель, который ссылается на другую копию репозитория, которая обычно размещается на удаленном сервере.

В некоторых ситуациях, например, когда удаленный репозиторий переносится на другой хост, вам необходимо изменить URL-адрес удаленного компьютера.

В этом руководстве объясняется, как изменить URL-адрес удаленного Git.

Изменение URL-адреса Git Remote

Каждый репозиторий Git может иметь ноль или более связанных с ним пультов Git. Когда вы клонируете репозиторий, имя пульта дистанционного управления автоматически устанавливается на origin и указывает на репозиторий, из которого вы клонировали. Если вы создали репозиторий локально, вы можете добавить новый пульт .

Пульт дистанционного управления может указывать на репозиторий, размещенный в службе хостинга Git, такой как GitHub, GitLab и BitBucket, или на ваш частный сервер Git .

Выполните следующие действия, чтобы изменить URL-адрес пульта дистанционного управления:

  1. Перейдите в каталог, в котором находится репозиторий:

     cd /path/to/repository
  2. Запустите git remote чтобы git remote список существующих пультов и просмотреть их имена и URL-адреса:

     git remote -v

    Результат будет выглядеть примерно так:

     origin https://github.com/user/repo_name.git (fetch) origin https://github.com/user/repo_name.git (push)
  3. Используйте команду git remote set-url за которой следует удаленное имя и удаленный URL-адрес:

     git remote set-url <remote-name> <remote-url>

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

    Если вы переходите на HTTPS, URL-адрес будет выглядеть примерно так:

     https://gitserver.com/user/repo_name.git

    Если вы переходите на SSH, URL-адрес будет выглядеть так:

    Например, чтобы изменить URL-адрес origin на [email protected]:user/repo_name.git , введите:

     git remote set-url origin [email protected]:user/repo_name.git
  4. Убедитесь, что URL-адрес удаленного устройства был успешно изменен, перечислив удаленные подключения:

     git remote -v

    Результат должен выглядеть так:

     origin ssh://[email protected]:user/repo_name.git (fetch) origin ssh://[email protected]:user/repo_name.git (push)

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

Команда git remote set-url обновляет файл .git/config репозитория с новым URL-адресом удаленного репозитория.

.git/config

...

[remote "origin"]
        url = [email protected]:user/repo_name.git
        fetch = +refs/heads/*:refs/remotes/origin/*

Вы также можете изменить URL-адрес пульта дистанционного управления, отредактировав файл .git/config в текстовом редакторе . Однако рекомендуется использовать команду git.

Выводы

Изменить URL-адрес удаленного Git так же просто, как запустить: git remote set-url <remote-name> <remote-url> .

Если вы столкнулись с проблемой или хотите оставить отзыв, оставьте комментарий ниже.

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

Команда git remote входит в состав системы, отвечающей за синхронизацию изменений. Записи, зарегистрированные с помощью команды git remote, используются в сочетании с командами git fetch, git push и git pull. Все эти команды отвечают за свою часть работы по выполнению синхронизации. Подробнее можно узнать, пройдя по соответствующим ссылкам.

git remote

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

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

Использование git remote для подключения к другим репозиториям

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

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

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

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

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

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

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

git remote add <name> <url>

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

Удаление подключения к удаленному репозиторию с именем <name>.

git remote rename <old-name> <new-name>

Переименование удаленного подключения с имени <old-name> на <new-name>.

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

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

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

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

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

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

http://host/path/to/repo.git

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

ssh://user@host/path/to/repo.git

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

Команды git remote

Команда git remote — одна из многих команд Git, которые принимают дополнительные «подкоманды». Ниже рассмотрены наиболее часто используемые подкоманды git remote.

Добавляет запись к ./.git/config для удаленного репозитория с именем <name> по URL-адресу <url>.

Принимает параметр -f, который запустит команду git fetch сразу после создания записи об удаленном репозитории.

Принимает параметр --tags, который немедленно запустит команду git fetch и импортирует все теги из удаленного репозитория.

Обновляет ./.git/config для переименования записи с <OLD> на <NEW>. При этом обновляются все удаленно отслеживаемые ветки и настройки конфигурации удаленного репозитория.

Изменяет ./.git/config и удаляет удаленный репозиторий с именем <NAME>. При этом удаляются все удаленно отслеживаемые ветки и настройки конфигурации удаленного репозитория.

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

Принимает параметр --push, поскольку URL-адреса чаще отправляют с помощью команды push, а не извлекают с помощью fetch.

При указании параметра --all будут перечислены все URL-адреса для данного удаленного репозитория.

Выводит общую информацию об удаленном репозитории с именем <NAME>.

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

Принимает параметр --dry-run, который выводит список удаляемых веток, но на самом деле не удаляет их.

Примеры git remote

Зачастую бывает удобно иметь подключение не только к репозиторию origin, но и к репозиториям коллег. Например, если ваш коллега Джон поддерживает общедоступный репозиторий на dev.example.com/john.git, вы можете добавить подключение следующим образом:

git remote add john http://dev.example.com/john.git

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

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

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

$ git remote
origin
upstream
other_users_repo

При вызове git remote с параметром -v будет выведен список закладок с именами и соответствующими URL-адресами репозиториев. Параметр -v расшифровывается как «verbose» — подробный. Ниже приведен пример подробного вывода команды git remote.

git remote -v
origin  git@bitbucket.com:origin_user/reponame.git (fetch)
origin  git@bitbucket.com:origin_user/reponame.git (push)
upstream    https://bitbucket.com/upstream_user/reponame.git (fetch)
upstream    https://bitbucket.com/upstream_user/reponame.git (push)
other_users_repo    https://bitbucket.com/other_users_repo/reponame (fetch)
other_users_repo    https://bitbucket.com/other_users_repo/reponame (push)

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

Команда git remote add используется для создания записи о новом подключении к удаленному репозиторию. После добавления удаленного репозитория имя можно использовать в качестве удобного ярлыка для адреса в других командах Git. Дополнительные сведения о принятом синтаксисе URL-адресов см. в разделе «URL-адреса репозиториев» ниже. Эта команда создаст новую запись в файле ./.git/config репозитория. Ниже приведен пример обновления этого файла конфигурации.

$ git remote add fake_test https://bitbucket.com/upstream_user/reponame.git; [remote "remote_test"] 
   url = https://bitbucket.com/upstream_user/reponame.git 
   fetch = +refs/heads/*:refs/remotes/remote_test/*

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

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

git remote show upstream
* remote upstream
   Fetch URL: https://bitbucket.com/upstream_user/reponame.git
   Push URL: https://bitbucket.com/upstream_user/reponame.git
   HEAD branch: main
   Remote branches:
      main tracked
      simd-deprecated tracked
      tutorial tracked
   Local ref configured for 'git push':
      main pushes to main (fast-forwardable)

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

После настройки записи об удаленном репозитории с помощью команды git remote с этим репозиторием можно связываться, передавая его имя в качестве аргумента другим командам Git. Для чтения данных из удаленного репозитория можно использовать и git fetch, и git pull. Эти команды выполняют разные операции (более подробную информацию можно узнать, пройдя по соответствующим ссылкам).

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

Для записи данных в удаленный репозиторий используется команда git push.

git push <remote-name> <branch-name>

В этом примере состояние локальной ветки <branch-name> передается в удаленный репозиторий, обозначенный как <remote-name>.

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

git remote rename <old-name> <new-name>

Принцип работы команды git remote rename очевиден из названия. В результате ее выполнения происходит переименование удаленного подключения с имени <old-name> на <new-name>. Кроме того, изменяется контент ./.git/config для переименования записи для удаленного репозитория.

Команда git remote rm удаляет подключение к удаленному репозиторию, обозначенному с помощью параметра <name>. Чтобы показать работу команды, «отменим» добавление из последнего примера. После выполнения команды git remote rm remote_test мы увидим, что запись [remote "remote_test"] удалена из контента ./.git/config.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Как изменить удаление букв
  • Как изменить уголовный кодекс
  • Как изменить угол эрекции
  • Как изменить угол углового дивана
  • Как изменить угол роста волос

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии