Что значит origin в команде git remote add origin?

Более простым языком, это название переменной, в которой хранится URL внешнего репозитория.
Получается такой псевдоним, чтобы не писать в командах полный URL.
Вместо origin можно использовать любое другое название. Внешних репозитория можно привязать несколько к локальному репо.
Ответы на вопрос 0
Ваш ответ на вопрос
Войдите, чтобы написать ответ

- Git
- +1 ещё
Как залить проект на гитхаб с сохранением папок?
- 1 подписчик
- 21 окт.
- 121 просмотр
What is «origin» in Git?
«origin» is the name of the remote repository where you want to publish you commits. By convention, the default remote repository is called «origin», but you can work with several remotes (with different names) as the same time. More information here (for example): gitref.org/remotes
Mar 2, 2012 at 7:25
Note also that origin is an «upstream» repo: see stackoverflow.com/questions/2739376/…
Mar 2, 2012 at 7:54
Possible duplicate of What’s the meaning of ‘origin’ in ‘git push origin master’
Jun 7, 2017 at 10:46
But then when using git fetch and then git branch -r local branches are prepended with origin/ ugh :-/ atlassian.com/git/tutorials/syncing/git-fetch
Mar 25, 2020 at 8:42
Checkout the .git\config file it contains the mappings of aliases to URLs, the .git folder is hidden by default.
May 22, 2020 at 1:11
12 Answers 12
origin is an alias on your system for a particular remote repository. It’s not actually a property of that repository.
git push origin branchname
you’re saying to push to the origin repository. There’s no requirement to name the remote repository origin : in fact the same repository could have a different alias for another developer.
Remotes are simply an alias that store the URL of repositories. You can see what URL belongs to each remote by using
git remote -v
In the push command, you can use remotes or you can simply use a URL directly. An example that uses the URL:
git push [email protected]:git/git.git master
30.8k 22 22 gold badges 106 106 silver badges 131 131 bronze badges
answered Mar 2, 2012 at 7:25
19.2k 5 5 gold badges 63 63 silver badges 66 66 bronze badges
Can a single remote be an alias for multiple other remotes? What if I wanted one remote to push to multiple other remotes? For example, push to a primary repo, and a push to a backup repo? Would that be a reasonable thing to want in some situations? EDIT: There are several solutions here.
Jul 21, 2017 at 7:07
What if I omit the «origin» keyword? When we say «git push», isn’t it anyway going to push all commits to the remote repository? Adding the keyword «origin» seems redundant.
Jul 28, 2019 at 13:47
@Mugen In the docs for git push you can see that it first checks the config for that repository (which you can check with git config —list ) for a key called branch.
Aug 11, 2019 at 3:33
origin is not the remote repository name. It is rather a local alias set as a key in place of the remote repository URL.
It avoids the user having to type the whole remote URL when prompting a push.
This name is set by default and for convention by Git when cloning from a remote for the first time.
This alias name is not hard coded and could be changed using following command prompt:
git remote rename origin mynewalias
Take a look at http://git-scm.com/docs/git-remote for further clarifications.
30.8k 22 22 gold badges 106 106 silver badges 131 131 bronze badges
answered Mar 28, 2014 at 12:19
Antoine Meltzheim Antoine Meltzheim
9,617 6 6 gold badges 35 35 silver badges 41 41 bronze badges
What if I omit the «origin» keyword? When we say «git push», isn’t it anyway going to push all commits to the remote repository? Adding the keyword «origin» seems redundant.
Jul 28, 2019 at 13:48
By default origin is already set, If you see «git remote -v»; Hence when you omit origin, it default connects to remote URL 🙂
Jan 25, 2022 at 4:26
Git has the concept of «remotes», which are simply URLs to other copies of your repository. When you clone another repository, Git automatically creates a remote named «origin» and points to it.
You can see more information about the remote by typing git remote show origin .
30.8k 22 22 gold badges 106 106 silver badges 131 131 bronze badges
answered Mar 2, 2012 at 7:26
Jason Malinowski Jason Malinowski
18.3k 1 1 gold badge 39 39 silver badges 55 55 bronze badges
git commands are very confusing to beginners. I guess it has to do with the history of this version control system. So, question: Instead of git remote show origin , why not simply git show origin ? There must be a reason, what is it? Thanks.
Aug 19, 2015 at 13:26
@Stack0verflow: this is probably better asked as a new question so people can do the research if you’re curious. ‘git show’ is already another command that shows a commit, and technically nothing would stop you having a branch called ‘origin’ in addition to having a remote called origin.
Aug 20, 2015 at 16:43
origin is the default alias to the URL of your remote repository.
15.5k 33 33 gold badges 114 114 silver badges 198 198 bronze badges
answered Mar 2, 2012 at 7:27
Jude Calimbas Jude Calimbas
2,764 2 2 gold badges 27 27 silver badges 24 24 bronze badges
Origin is the shortname that acts like an alias for the url of the remote repository.
Let me explain with an example.
Suppose you have a remote repository called amazing-project and then you clone that remote repository to your local machine so that you have a local repository . Then you would have something like what you can see in the diagram below:

Because you cloned the repository. The remote repository and the local repository are linked.

If you run the command git remote -v it will list all the remote repositories that are linked to your local repository. There you will see that in order to push or fetch code from your remote repository you will use the shortname ‘origin’.
Now, this may be a bit confusing because in GitHub (or the remote server) the project is called ‘amazing-project’. So why does it seem like there are two names for the remote repository?

Well one of the names that we have for our repository is the name it has on GitHub or a remote server somewhere. This can be kind of thought like a project name. And in our case that is ‘amazing-project’.
The other name that we have for our repository is the shortname that it has in our local repository that is related to the URL of the repository. It is the shortname we are going to use whenever we want to push or fetch code from that remote repository. And this shortname kind of acts like an alias for the url, it’s a way for us to avoid having to use that entire long url in order to push or fetch code. And in our example above it is called origin .
So, what is origin ?
Basically origin is the default shortname that Git uses for a remote repository when you clone that remote repository. So it’s just the default.
In many cases you will have links to multiple remote repositories in your local repository and each of those will have a different shortname.
So final question, why don’t we just use the same name?
I will answer that question with another example. Suppose we have a friend who forks our remote repository so they can help us on our project. And let’s assume we want to be able to fetch code from their remote repository. We can use the command git remote add in order to add a link to their remote repository in our local repository.

In the above image you can see that I used the shortname friend to refer to my friend’s remote repository. You can also see that both of the remote repositories have the same project name amazing-project and that gives us one reason why the remote repository names in the remote server and the shortnames in our local repositories should not be the same!
There is a really helpful video that explains all of this that can be found here.
10.5 Git изнутри — Спецификации ссылок
На протяжении всей книги мы использовали довольно простые соответствия между локальными ветками и ветками в удалённых репозиториях, но всё может быть чуть сложнее. Допустим, вы добавили удалённый репозиторий:
$ git remote add origin https://github.com/schacon/simplegit-progit
Эта команда добавляет секцию в файл .git/config , в которой заданы имя удалённого репозитория ( origin ), его URL и спецификация ссылок для извлечения данных:
[remote "origin"] url = https://github.com/schacon/simplegit-progit fetch = +refs/heads/*:refs/remotes/origin/*
Формат спецификации следующий: опциональный + , далее пара : , где — шаблон ссылок в удалённом репозитории, а — соответствующий шаблон локальных ссылок. Символ + сообщает Git, что обновление необходимо выполнять даже в том случае, если оно не является простым смещением.
По умолчанию, после выполнения git remote add origin , Git забирает все ссылки из refs/heads/ на сервере, и записывает их в refs/remotes/origin/ локально. Таким образом, если на сервере есть ветка master , историю данной ветки можно получить, выполнив любую из следующих команд:
$ git log origin/master $ git log remotes/origin/master $ git log refs/remotes/origin/master
Все эти команды эквивалентны, так как Git развернёт каждую запись до refs/remotes/origin/master .
Если хочется, чтобы Git забирал при обновлении только ветку master , а не все доступные на сервере, можно изменить соответствующую строку в конфигурации:
fetch = +refs/heads/master:refs/remotes/origin/master
Эта настройка будет использоваться по умолчанию при вызове git fetch для данного удалённого репозитория. Если же вам нужно изменить спецификацию всего раз, можно задать конкретное соответствие веток в командной строке. Например, чтобы получить данные из ветки master из удалённого репозитория в локальную origin/mymaster , можно выполнить:
$ git fetch origin master:refs/remotes/origin/mymaster
Можно задать несколько спецификаций за один раз. Получить данные нескольких веток из командной строки можно так:
$ git fetch origin master:refs/remotes/origin/mymaster \ topic:refs/remotes/origin/topic From git@github.com:schacon/simplegit ! [rejected] master -> origin/mymaster (non fast forward) * [new branch] topic -> origin/topic
В данном случае слияние ветки master выполнить не удалось, поскольку слияние не было простым смещением вперёд. Такое поведение можно изменить, добавив перед спецификацией знак + .
В конфигурационном файле также можно задавать несколько спецификаций для получения обновлений. Чтобы каждый раз получать обновления веток master и experiment из репозитория origin , добавьте следующие строки:
[remote "origin"] url = https://github.com/schacon/simplegit-progit fetch = +refs/heads/master:refs/remotes/origin/master fetch = +refs/heads/experiment:refs/remotes/origin/experiment
Начиная с версии Git 2.6.0 можно указывать шаблоны спецификаций, соответствующие нескольким веткам:
fetch = +refs/heads/qa*:refs/remotes/origin/qa*
Для достижения аналогичного результата можно так же использовать пространства имён (или каталоги). Если ваша QA команда использует несколько веток для своей работы и вы хотите получать только ветку master и все ветки команды QA, то можно добавить в конфигурацию следующее:
[remote "origin"] url = https://github.com/schacon/simplegit-progit fetch = +refs/heads/master:refs/remotes/origin/master fetch = +refs/heads/qa/*:refs/remotes/origin/qa/*
Если у вас сложный рабочий процесс при котором все команды — разработчики, QA и специалисты по внедрению — ведут работы в одном репозитории, вы можете разграничить их с помощью пространств имён.
Спецификации ссылок для отправки данных на сервер
Здорово, что можно получать данные по ссылкам в отдельных пространствах имён, но нам же ещё надо сделать так, чтобы команда QA сначала смогла отправить свои ветки в пространство имён qa/ . Мы решим эту задачу, используя спецификации ссылок для команды push .
Если команда QA хочет отправлять изменения из локальной ветки master в qa/master на удалённом сервере, они могут использовать такой приём:
$ git push origin master:refs/heads/qa/master
Если же они хотят, чтобы Git автоматически делал так при вызове git push origin , можно добавить в конфигурационный файл значение для push :
[remote "origin"] url = https://github.com/schacon/simplegit-progit fetch = +refs/heads/*:refs/remotes/origin/* push = refs/heads/master:refs/heads/qa/master
Аналогично, это приведёт к тому, что при вызове git push origin локальная ветка master будет по умолчанию отправляться в удалённую ветку qa/master .
Примечание
Вы не можете использовать спецификации ссылок, чтобы получать данные из одного репозитория, а отправлять в другой. Для реализации такого поведения обратитесь к разделу Поддержание GitHub репозитория в актуальном состоянии главы 6.
Удаление ссылок
Кроме того, спецификации ссылок можно использовать для удаления ссылок на удалённом сервере:
$ git push origin :topic
Так как спецификация ссылки задаётся в виде : , то, пропуская , мы указываем Git, что указанную ветку на удалённом сервере надо сделать пустой, что приводит к её удалению.
Начиная с версии Git v1.7.0, можно использовать следующий синтаксис:
$ git push origin --delete topic
Управление удаленными репозиториями
Узнайте, как работать с локальными репозиториями на компьютере и удаленными репозиториями, размещенными в GitHub.
Platform navigation
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/OWNER/REPOSITORY.git
$ git remote add origin https://github.com/OWNER/REPOSITORY.git # Set a new remote $ git remote -v # Verify new remote > origin https://github.com/OWNER/REPOSITORY.git (fetch) > origin https://github.com/OWNER/REPOSITORY.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.
Tip: For information on the difference between HTTPS and SSH URLs, see «About remote repositories.»
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/OWNER/REPOSITORY.git- If you’re updating to use SSH, your URL might look like:
git@github.com:OWNER/REPOSITORY.gitSwitching remote URLs from SSH to HTTPS
- Open Terminal Terminal Git Bash .
- Change the current working directory to your local project.
- List your existing remotes in order to get the name of the remote you want to change.
$ git remote -v > origin git@github.com:OWNER/REPOSITORY.git (fetch) > origin git@github.com:OWNER/REPOSITORY.git (push)git remote set-url origin https://github.com/OWNER/REPOSITORY.git$ git remote -v # Verify new remote URL > origin https://github.com/OWNER/REPOSITORY.git (fetch) > origin https://github.com/OWNER/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 «Managing your personal access tokens.»
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
- Open Terminal Terminal Git Bash .
- Change the current working directory to your local project.
- List your existing remotes in order to get the name of the remote you want to change.
$ git remote -v > origin https://github.com/OWNER/REPOSITORY.git (fetch) > origin https://github.com/OWNER/REPOSITORY.git (push)git remote set-url origin git@github.com:OWNER/REPOSITORY.git$ git remote -v # Verify new remote URL > origin git@github.com:OWNER/REPOSITORY.git (fetch) > origin git@github.com:OWNER/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