Как удалить внешний репозиторий origin
Перейти к содержимому

Как удалить внешний репозиторий origin

  • автор:

Как удалить внешний репозиторий origin

Git doesn’t have a central server like Subversion. All of the commands so far have been done locally, just updating a local database. To collaborate with other developers in Git, you have to put all that data on a server that the other developers have access to. The way Git does this is to synchronize your data with another repository. There is no real difference between a server and a client — a Git repository is a Git repository and you can synchronize between any two easily.

Once you have a Git repository, either one that you set up on your own server, or one hosted someplace like GitHub, you can tell Git to either push any data that you have that is not in the remote repository up, or you can ask Git to fetch differences down from the other repo.

You can do this any time you are online, it does not have to correspond with a commit or anything else. Generally you will do a number of commits locally, then fetch data from the online shared repository you cloned the project from to get up to date, merge any new work into the stuff you did, then push your changes back up.

In a nutshell you can update your project with git fetch and share your changes with git push . You can manage your remote repositories with git remote .

docs book git remote list, add and delete remote repository aliases

Unlike centralized version control systems that have a client that is very different from a server, Git repositories are all basically equal and you simply synchronize between them. This makes it easy to have more than one remote repository — you can have some that you have read-only access to and others that you can write to as well.

So that you don’t have to use the full URL of a remote repository every time you want to synchronize with it, Git stores an alias or nickname for each remote repository URL you are interested in. You use the git remote command to manage this list of remote repos that you care about.

git remote list your remote aliases

Without any arguments, Git will simply show you the remote repository aliases that it has stored. By default, if you cloned the project (as opposed to creating a new one locally), Git will automatically add the URL of the repository that you cloned from under the name ‘origin’. If you run the command with the -v option, you can see the actual URL for each alias.

You see the URL there twice because Git allows you to have different push and fetch URLs for each remote in case you want to use different protocols for reads and writes.

git remote add add a new remote repository of your project

If you want to share a locally created repository, or you want to take contributions from someone else’s repository — if you want to interact in any way with a new repository, it’s generally easiest to add it as a remote. You do that by running git remote add [alias] [url] . That adds [url] under a local remote named [alias] .

For example, if we want to share our Hello World program with the world, we can create a new repository on a server (Using GitHub as an example), which should give you a URL, in this case «git@github.com:schacon/hw.git». To add that to our project so we can push to it and fetch updates from it we would do this:

Like the branch naming, remote alias names are arbitrary — just as ‘master’ has no special meaning but is widely used because git init sets it up by default, ‘origin’ is often used as a remote name because git clone sets it up by default as the cloned-from URL. In this case we’ll name the remote ‘github’, but you could name it just about anything.

git remote rm removing an existing remote alias

Git addeth and Git taketh away. If you need to remove a remote — you are not using it anymore, the project is gone, etc — you can remove it with git remote rm [alias] .

git remote rename [old-alias] [new-alias] rename remote aliases

If you want to rename remote aliases without having to delete them and add them again you can do that by running git remote rename [old-alias] [new-alias] . This will allow you to modify the current name of the remote.

In a nutshell with git remote you can list our remote repositories and whatever URL that repository is using. You can use git remote add to add new remotes, git remote rm to delete existing ones or git remote rename [old-alias] [new-alias] to rename them.

git remote set-url update an existing remote URL

Should you ever need to update a remote’s URL, you can do so with the git remote set-url command.

In addition to this, you can set a different push URL when you include the —push flag. This allows you to fetch from one repo while pushing to another and yet both use the same remote alias.

Internally, the git remote set-url command calls git config remote , but has the added benefit of reporting back any errors. git config remote on the other hand, will silently fail if you mistype an argument or option and not actually set anything.

For example, we’ll update the github remote but instead reference it as guhflub in both invocations.

In a nutshell, you can update the locations of your remotes with git remote set-url . You can also set different push and fetch URLs under the same remote alias.

docs book git fetch download new branches and data from a remote repository

docs book git pull fetch from a remote repo and try to merge into the current branch

Git has two commands to update itself from a remote repository. git fetch will synchronize you with another repo, pulling down any data that you do not have locally and giving you bookmarks to where each branch on that remote was when you synchronized. These are called «remote branches» and are identical to local branches except that Git will not allow you to check them out — however, you can merge from them, diff them to other branches, run history logs on them, etc. You do all of that stuff locally after you synchronize.

The second command that will fetch down new data from a remote server is git pull . This command will basically run a git fetch immediately followed by a git merge of the branch on that remote that is tracked by whatever branch you are currently in. Running the fetch and merge commands separately involves less magic and less problems, but if you like the idea of pull , you can read about it in more detail in the official docs.

Assuming you have a remote all set up and you want to pull in updates, you would first run git fetch [alias] to tell Git to fetch down all the data it has that you do not, then you would run git merge [alias]/[branch] to merge into your current branch anything new you see on the server (like if someone else has pushed in the meantime). So, if you were working on a Hello World project with several other people and wanted to bring in any changes that had been pushed since we last connected, we would do something like this:

Here we can see that since we last synchronized with this remote, five branches have been added or updated. The ‘ada’ and ‘lisp’ branches are new, where the ‘master’, ‘c-langs’ and ‘java’ branches have been updated. In our example case, other developers are pushing proposed updates to remote branches for review before they’re merged into ‘master’.

You can see the mapping that Git makes. The ‘master’ branch on the remote repository becomes a branch named ‘github/master’ locally. That way you can merge the ‘master’ branch on that remote into the local ‘master’ branch by running git merge github/master . Or, you can see what new commits are on that branch by running git log github/master ^master . If your remote is named ‘origin’ it would be origin/master instead. Almost any command you would run using local branches you can use remote branches with too.

If you have more than one remote repository, you can either fetch from specific ones by running git fetch [alias] or you can tell Git to synchronize with all of your remotes by running git fetch —all .

In a nutshell you run git fetch [alias] to synchronize your repository with a remote repository, fetching all the data it has that you do not into branch references locally for merging and whatnot.

docs book git push push your new branches and data to a remote repository

To share the cool commits you’ve done with others, you need to push your changes to the remote repository. To do this, you run git push [alias] [branch] which will attempt to make your [branch] the new [branch] on the [alias] remote. Let’s try it by initially pushing our ‘master’ branch to the new ‘github’ remote we created earlier.

Pretty easy. Now if someone clones that repository they will get exactly what we have committed and all of its history.

What if you have a topic branch like the ‘erlang’ branch created earlier and want to share just that? You can just push that branch instead.

Now when people clone or fetch from that repository, they’ll get an ‘erlang’ branch they can look at and merge from. You can push any branch to any remote repository that you have write access to in this way. If your branch is already on the server, it will try to update it, if it is not, Git will add it.

The last major issue you run into with pushing to remote branches is the case of someone pushing in the meantime. If you and another developer clone at the same time, you both do commits, then she pushes and then you try to push, Git will by default not allow you to overwrite her changes. Instead, it basically runs git log on the branch you’re trying to push and makes sure it can see the current tip of the server’s branch in your push’s history. If it can’t see what is on the server in your history, it concludes that you are out of date and will reject your push. You will rightly have to fetch, merge then push again — which makes sure you take her changes into account.

This is what happens when you try to push a branch to a remote branch that has been updated in the meantime:

You can fix this by running git fetch github; git merge github/master and then pushing again.

In a nutshell you run git push [alias] [branch] to update a remote repository with the changes you’ve made locally. It will take what your [branch] looks like and push it to be [branch] on the remote, if possible. If someone else has pushed since you last fetched and merged, the Git server will deny your push until you are up to date.

2.5 Основы Git — Работа с удалёнными репозиториями

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Когда вы клонируете репозиторий, команда 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 , вы получите следующий результат:

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

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

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

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

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

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

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

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

Git Remove Remote: A Guide

Have you set the wrong remote for a Git repository? Do you need to change your remote? Not to worry, Git has you covered. In Git, there’s a command called git remote remove that you can use to remove a remote from a repository.

This guide will cover everything you need to know about removing a git remote using git remote remove. We’ll walk through an example to help you get started using this command.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest
First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy , and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

What is a Git Remote?

Git remote is a reference that points to the remote version of a Git repository.

Remember, Git is a distributed version control system . This means that you can download a copy of a Git repository on your local machine and make changes. These changes do not affect the main copy of a repository – the remote copy – until you “push” them to the remote repository.

For the most part, you’ll have one remote Git branch which is named origin . When you start a GitHub repository, for example, the instructions you’ll be asked to set up a remote named origin. You can change it, but origin is the default value.

With that said, you may need to change your remote at some point. That’s where the git remote remove command comes in handy.

Git Remove Remote: A Guide

The git remote remove command removes a remote from a local repository. You can use the shorter git remote rm command too. The syntax for this command is: git remote rm <remote-url>.

If you remove a remote accidentally, you will need to add it back manually using the git remote add command.

The git remote rm command does not remove a remote from a remote repository. This is because remote repositories do not keep track of your local remotes. A remote is local to your computer.

How to Remove Remote Origin in Git

Let’s remove a Git remote from a repository! To start, move into your repository directory. Then execute the following command:

To delete the origin remote from your repository, use this command:

Upon executing this command, the reference remotes origin will no longer point to the remote repository. It’s worth noting this does not delete your remote repository or affect it in any way. All it means is that your local copy of a repository is no longer associated with a particular remote.

Alternatively, you can use the git remote rm command. git remote rm is simply a shorter version of the git remote remove command.

Venus, a software engineer at Rockbot

«Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!»

Venus, Software Engineer at Rockbot

Find Your Bootcamp Match

You can use the git remove -v command to verify if a remote has been removed. The -v flag shows the URLs to which each origin points. When you run this command, you’ll see something like this:

We can see our “origin” remote has been successfully removed. But, our “new” origin remains.

Git Update Remote URL

There’s no need to remove a remote if you just need to update its URL. You can update a Git remote using the git remote set-url command.

Let’s say that you want to change the URL of a particular remote. We want to set the value of the origin pointer to:

We could do so by specifying the URL for the remote we want to use:

This will modify our origin pointer to refer to the new URL we have specified. We can check if this change has been made by using the git remote -v command like we did earlier.

To learn more about changing remotes, check out our How to Change a Git Remote guide .

Conclusion

The git remove remote command allows you to remove a pointer to a remote repository from the Git command line. You can use the git remote set-url command to change the value of a remote if you only need to amend its URL.

Now you’re ready to start removing and updating remotes like an expert developer!

Do you want to learn more about Git? Check out our complete How to Learn Git guide for expert tips and guidance on top online learning resources.

About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.

How to remove remote origin from a Git repository

I just did git init to initialize my folder as Git repository and then added a remote repository using git remote add origin URL . Now I want to remove this git remote add origin and add a new repository git remote add origin new-URL . How can I do it?

Peter Mortensen's user avatar

16 Answers 16

Instead of removing and re-adding, you can do this:

To remove remote use this:

If you insist on deleting it:

Or if you have Git version 1.7.10 or older

1615903's user avatar

To remove a remote:

To add a remote:

Vontei's user avatar

you can try this out,if you want to remove origin and then add it:

I don’t have enough reputation to comment answer of @user1615903, so add this as answer: «git remote remove» does not exist, should use «rm» instead of «remove». So the correct way is:

heroin's user avatar

if multiple remotes are set for a project like heroku and own repository then use the below command to check the available remote URLs inside the local project directory

it will display all the remote URLs like

if you want to remove heroku remote then,

it will remove heroku remote only if want to remove own remote repository

Mohamed Saheed Mohamed Riswan's user avatar

To remove just use this command

You can rename (changing URL of a remote repository) using :

Too permanently delete the remote repository use :

Anshul Bisht's user avatar

To set a origins remote url-

here origin is your push url name. You may have multiple origin. If you have multiple origin replace origin as that name.

For deleting Origin

For adding new origin

Nasir Khan's user avatar

perhaps I am late you can use git remote remove origin it will do the job.

Krishna Kamal's user avatar

Cancel local git repository(Warning: This removes the history)

Then; Create git repostory again

Then; Repeat the remote repo connect

A warning though: This removes the history.

first will change push remote url

second will change fetch remote url

Hamit YILDIRIM's user avatar

You can go to the .git folder, edit the config file without using the commands.

Git aliases has been life saver:

Note: Default name origin if it is different than update according to your needs. I usually have "origin" for all repos

Step-1: Define git aliases ->

This command will help to view your existing "origin" and remote "URL"

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

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