How to connect to remote git repository
How to connect to remote git repository
git syncing
SVN uses a single centralized repository to serve as the communication hub for developers, and collaboration takes place by passing changesets between the developers’ working copies and the central repository. This is different from Git’s distributed collaboration model, which gives every developer their own copy of the repository, complete with its own local history and branch structure. Users typically need to share a series of commits rather than a single changeset. Instead of committing a changeset from a working copy to the central repository, Git lets you share entire branches between repositories.
Git remote
The git remote command lets you create, view, and delete connections to other repositories. Remote connections are more like bookmarks rather than direct links into other repositories. Instead of providing real-time access to another repository, they serve as convenient names that can be used to reference a not-so-convenient URL.
For example, the following diagram shows two remote connections from your repo into the central repo and another developer’s repo. Instead of referencing them by their full URLs, you can pass the origin and john shortcuts to other Git commands.
Git remote usage overview
Viewing git remote configurations
List the remote connections you have to other repositories.
Same as the above command, but include the URL of each connection.
Creating and modifying git remote configurations
Create a new connection to a remote repository. After adding a remote, you’ll be able to use <name> as a convenient shortcut for <url> in other Git commands.
Git remote discussion
Git is designed to give each developer an entirely isolated development environment. This means that information is not automatically passed back and forth between repositories. Instead, developers need to manually pull upstream commits into their local repository or manually push their local commits back up to the central repository. The git remote command is really just an easier way to pass URLs to these «sharing» commands.
The origin Remote
Repository URLs
Git supports many ways to reference a remote repository. Two of the easiest ways to access a remote repo are via the HTTP and the SSH protocols. HTTP is an easy way to allow anonymous, read-only access to a repository. For example:
But, it’s generally not possible to push commits to an HTTP address (you wouldn’t want to allow anonymous pushes anyways). For read-write access, you should use SSH instead:
You’ll need a valid SSH account on the host machine, but other than that, Git supports authenticated access via SSH out of the box. Modern secure 3rd party hosting solutions like Bitbucket.com will provide these URLs for you.
Git remote commands
The git remote command is one of many Git commands that takes additional appended ‘subcommands’. Below is an examination of the commonly used git remote subcommands.
Outputs the URLs for a remote record.
Deletes any local branches for <NAME> that are not present on the remote repository.
Git remote examples
Having this kind of access to individual developers’ repositories makes it possible to collaborate outside of the central repository. This can be very useful for small teams working on a large project.
Showing your remotes
By default, the git remote command will list previously stored remote connections to other repositories. This will produce single line output that lists the names of «bookmark» name of remote repos.
Adding Remote Repositories
Inspecting a Remote
The show subcommand can be appended to git remote to give detailed output on the configuration of a remote. This output will contain a list of branches associated with the remote and also the endpoints attached for fetching and pushing.
Fetching and pulling from Git remotes
Pushing to Git remotes
The git push command is used to write to a remote repository.
Renaming and Removing Remotes
How to connect to a remote Git repository?
I am working with a team and we want to use Git (Not with GitHub, we have a private remote machine). We were using SVN until now. We have a remote machine that works like an SVN repository. Now, we want to turn this machine into the Git central repository. By what I have read, what everyone needs to do on their machines, is to install Git and use the following command to add the remote main repository:
5 Answers 5
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
It’s simple and follow the small Steps to proceed:
git remote add origin username@189.14.666.666:/home/ubuntu/workspace/project.git
Below is an optional command but found it has been suggested as i was working to setup the same thing
This should work fine and will push the local code to the remote git repository.
You can also use an alternative way, after creating the project.git folder on git, clone the project and copy the entire content into that folder. Commit the changes and it should be the same way. While cloning make sure you have access or the key being is the secret key for the remote server being used for deployment.
Now, if the repository is already existing on a remote machine, and you do not have anything locally, you do git clone instead.
The URL format is simple, it is PROTOCOL:/[user@]remoteMachineAddress/path/to/repository.git
For example, cloning a repository on a machine to which you have SSH access using the «dev» user, residing in /srv/repositories/awesomeproject.git and that machine has the ip 10.11.12.13 you do:
Like you said remote_repo_url is indeed the IP of the server, and yes it needs to be added on each PC, but it’s easier to understand if you create the server first then ask each to clone it.
There’s several ways to connect to the server, you can use ssh, http, or even a network drive, each has it’s pros and cons. You can refer to the documentation about protocols and how to connect to the server
You can check the rest of chapter 4 for more detailed information, as it’s talking about how to set up your own server
To me it sounds like the simplest way to expose your git repository on the server (which seems to be a Windows machine) would be to share it as a network resource.
Right click the folder «MY_GIT_REPOSITORY» and select «Sharing». This will give you the ability to share your git repository as a network resource on your local network. Make sure you give the correct users the ability to write to that share (will be needed when you and your co-workers push to the repository).
Git. Урок 6.
Работа с удаленным репозиторием.
Модель ветвления.
Команды: clone, fetch, push, pull.
1. Что такое удаленный репозиторий.
2. Настройка подключения удаленного репозитория. Группа команд git remote.
2.1. Добавление удаленного репозитория к существующему локальному. Команда git remote add.
2.2. Настройка подключения по HTTPS.
2.3. Настройка подключения по SSH.
2.4. Отключение удаленного репозитория от локального. Команда git remote remove.
2.5. Изменение имени удаленного репозитория. Просмотр всех удаленных репозиториев. Команды git remote rename, git remote show.
3. Клонирование удаленного репозитория. Команда git clone.
4. Получение изменений из удаленного репозитория. Команда git fetch.
5. Получение изменений из удаленного репозитория. Команда git pull.
6. Отправка изменений в удаленный репозиторий. Команда git push.
7. GitHub. Работа с репозиторием, создание форков и пулл-реквестов
7.1 Создание репозитория на GitHub
7.2 Страница репозитория на GitHub.
7.3. Создание форка репозитория на GitHub. Пулл-реквесты.
8. Модель ветвления Git
8.1. Центральный репозиторий
8.2. Основные ветки
8.3. Вспомогательные ветки
8.4. Feature-ветки.
8.5. Release-ветки.
8.6. Hotfix-ветки.
Как мы уже говорили в первом уроке, один из плюсов распределенной системы контроля версий заключается в том, что у вас может быть сколь угодно много удаленных репозиториев. Какие-то из них могут быть доступны только на чтение, а какие-то – на чтение и запись.
Таким образом, чтобы стать полноценным пользователем Git, важно овладеть навыками работы с удаленным репозиторием. Среди них – создание новых и копирование к себе уже существующих удаленных репозиториев, загрузка на сервер локальных коммитов и скачивание изменения с сервера. Давайте изучим все это по порядку.
Необходимость подключить удаленный репозиторий к уже существующему локальному возникает в ситуациях, когда вы решаете выгрузить уже написанный код на удаленный сервер. Это нужно, чтобы другие разработчики смогли получить к нему доступ или чтобы вы сами могли заниматься разработкой с нескольких компьютеров (например, домашнего и рабочего).
2.1. Добавление удаленного репозитория к существующему локальному. Команда git remote add.
Команда git remote add
Возможно у вас возникнут вопросы: что такое имя удаленного репозитория, и откуда взять ссылку на него. Ответим на них по порядку.
Имя удаленного репозитория в команде git remote add вы можете придумать сами. Впоследствии, при работе с этим удаленным репозиторием, вы будете обращаться к нему по придуманному имени. Принято называть удаленный репозиторий origin, но строго говоря, никаких ограничений здесь нет.
Со ссылкой на удаленный репозиторий тоже все просто. Мы работаем с GitHub, поэтому эту ссылку можно взять, нажав на большую зеленую кнопку Code на странице репозитория на GitHub.
Вам предложат выбрать одну из трех ссылок: для протоколов https и ssh и для клиента GitHub на компьютер. Вот примеры этих трех ссылок для репозитория geometric_lib известного вам по практическим занятиям этого курса:
Итак, с последней ссылкой все понятно: ее нужно использовать в специальной программе для компьютера с графическим UI от создателей GitHub. Но в чем разница между первыми двумя?
2.2. Настройка подключения по HTTPS
Итак, чтобы создать токен персонального доступа, следуйте инструкции:
1. Подтвердите свой email-адрес, который вы использовали при регистрации аккаунта GitHub (если он не подтвержден
2.3. Настройка подключения по SSH
После останется только загрузить наш публичный ключ на GitHub и готово. Давайте рассмотрим этот процесс подробнее:
/.ssh/id_ed25519
5. Отлично, последний этап: добавляем публичный ключ на GitHub. Для этого откройте файл с публичным ключом (он должен иметь расширение .pub ). Если вы оставили путь по умолчанию, то ваш ключ будет располагаться по адресу
11. Скопированный ключ вставьте в раздел Key (ключ)
12. Нажмите Add SSH key (добавить ssh-ключ)
13. Возможно потребуется ввести пароль для подтверждения действия.
Теперь SSH-ключ добавлен. Вам больше не нужно вводить имя пользователя и пароль при каждой загрузке или скачивании изменений из удаленного репозитория.
2.4. Отключение удаленного репозитория от локального. Команда git remote remove.
Команда git remote remove
2.5. Изменение имени удаленного репозитория. Просмотр всех удаленных репозиториев. Команды git remote rename, git remote show.
Команда git remote rename
Команда git remote show
Теперь, когда мы разобрались с настройкой подключения удаленного репозитория к уже существующему, давайте узнаем, как можно склонировать удаленный репозиторий к себе на компьютер. Операция клонирования создаёт на вашем компьютере точную копию удаленного репозитория.
Команда git clone
Ссылку на удаленный репозиторий можно получить тем же способом, что мы разбирали выше. Нужно нажать на зеленую кнопку Code на главной странице репозитория на GitHub.
Теперь, когда мы научились подключать удаленный репозиторий к локальному и клонировать его к себе на компьютер, пора узнать, как же получить изменения из удаленного репозитория.
У вас может возникнуть вопрос: зачем получать изменения, если только я загружаю их в свой удаленный репозиторий? Все верно, если вы работаете один, то вряд ли вам пригодится загружать изменения из удаленного репозитория в локальный. Но если вы работаете в команде, вы будете по несколько раз в день обновлять свой репозиторий, загружая в него коммиты, сделанные другими разработчиками из вашей команды.
Команда git fetch
В выводе команды видно, что она скачала несколько объектов, а из последней строчки мы узнаем, что ветка develop удаленного репозитория была записана в ветку origin/develop на нашем компьютере.
Давайте посмотрим, как теперь выглядит история и рабочая копия локального репозитория.
Команда git pull
Команда git push
—all
Пушит все имеющиеся ветки
—force-with-lease
Удаляет все коммиты, которых нет в локальном репозитории. Если коммит, который команда соберется удалять был создан другим пользователем, то выполнение закончится с ошибкой.
Давайте более подробно разберем, как работает эта команда. Допустим, мы выполнили git push origin develop в нашем локальном репозитории. Возможны три варианта развития событий.
Если на удаленной ветке есть коммиты, которые были сделаны позже наших, то есть слияние в режиме fast-forward выполнить невозможно, то команда завершится с ошибкой. Ведь в этом случае есть угроза перезаписи истории удаленного репозитория и удаления всех коммитов, созданных позже наших.
7.1 Создание репозитория на GitHub
Прежде всего вам необходимо зарегистрироваться на GitHub, но это довольно тривиальный процесс, так что его мы здесь опустим. После регистрации вы попадете на главную страницу. На ней будут отображаться действия людей, на которых вы подписались и обновления в репозиториях, которые вы добавили в избранное.
Перед вами откроется страница создания репозитория. Давайте разберем, что за поля нам предлагают заполнить.
7.2 Страница репозитория на GitHub.
Кстати, можно заметить, что содержимое файла README выводится под рабочей копией репозитория. Это одна из особенностей GitHub. Вы в любое время можете создать файл с именем README.md и запушить его в свой удаленный репозиторий на GitHub. Тогда содержимое этого файла будет отображаться прямо на странице вашего репозитория.
В верхнем меню мы видим 9 разных вкладок. Давайте разберем их по порядку.
Working with Remotes
To be able to collaborate on any Git project, you need to know how to manage your remote repositories. Remote repositories are versions of your project that are hosted on the Internet or network somewhere. You can have several of them, each of which generally is either read-only or read/write for you. Collaborating with others involves managing these remote repositories and pushing and pulling data to and from them when you need to share work. Managing remote repositories includes knowing how to add remote repositories, remove remotes that are no longer valid, manage various remote branches and define them as being tracked or not, and more. In this section, we’ll cover some of these remote-management skills.
Showing Your Remotes
To see which remote servers you have configured, you can run the git remote command. It lists the shortnames of each remote handle you’ve specified. If you’ve cloned your repository, you should at least see origin – that is the default name Git gives to the server you cloned from:
If you have more than one remote, the command lists them all. For example, a repository with multiple remotes for working with several collaborators might look something like this.
This means we can pull contributions from any of these users pretty easily. We may additionally have permission to push to one or more of these, though we can’t tell that here.
Notice that these remotes use a variety of protocols; we’ll cover more about this in Getting Git on a Server.
Adding Remote Repositories
I’ve mentioned and given some demonstrations of adding remote repositories in previous sections, but here is how to do it explicitly. To add a new remote Git repository as a shortname you can reference easily, run git remote add [shortname] [url] :
Now you can use the string pb on the command line in lieu of the whole URL. For example, if you want to fetch all the information that Paul has but that you don’t yet have in your repository, you can run git fetch pb :
Paul’s master branch is now accessible locally as pb/master – you can merge it into one of your branches, or you can check out a local branch at that point if you want to inspect it. (We’ll go over what branches are and how to use them in much more detail in [ch03-git-branching].)
Fetching and Pulling from Your Remotes
As you just saw, to get data from your remote projects, you can run:
The command goes out to that remote project and pulls down all the data from that remote project that you don’t have yet. After you do this, you should have references to all the branches from that remote, which you can merge in or inspect at any time.
If you clone a repository, the command automatically adds that remote repository under the name “origin”. So, git fetch origin fetches any new work that has been pushed to that server since you cloned (or last fetched from) it. It’s important to note that the git fetch command pulls the data to your local repository – it doesn’t automatically merge it with any of your work or modify what you’re currently working on. You have to merge it manually into your work when you’re ready.
If you have a branch set up to track a remote branch (see the next section and [ch03-git-branching] for more information), you can use the git pull command to automatically fetch and then merge a remote branch into your current branch. This may be an easier or more comfortable workflow for you; and by default, the git clone command automatically sets up your local master branch to track the remote master branch (or whatever the default branch is called) on the server you cloned from. Running git pull generally fetches data from the server you originally cloned from and automatically tries to merge it into the code you’re currently working on.
Pushing to Your Remotes
This command works only if you cloned from a server to which you have write access and if nobody has pushed in the meantime. If you and someone else clone at the same time and they push upstream and then you push upstream, your push will rightly be rejected. You’ll have to pull down their work first and incorporate it into yours before you’ll be allowed to push. See [ch03-git-branching] for more detailed information on how to push to remote servers.
Inspecting a Remote
That is a simple example you’re likely to encounter. When you’re using Git more heavily, however, you may see much more information from git remote show :
Removing and Renaming Remotes
If you want to remove a remote for some reason – you’ve moved the server or are no longer using a particular mirror, or perhaps a contributor isn’t contributing anymore – you can use git remote rm :
Connect a local repository with a remote repository
I have a local repository. I created the whole application, but now I want to push it to a remote repository. I already have remote repo as well. How can I connect these two repositories without losing any work that I did?
4 Answers 4
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
A one line exact answer is provided by vergenzt, but if you want to go through the details on how to commit your code and connect a local and remote GitHub repository and push code into the remote repository using Git CLI, you can go through this article: Beginners guide to Git using CLI
First make this command:
Then tab this command:
Note the name of master is the name of the remote repository on GitHub. If it has another name, like main or something else, make it instead of master.
It’s expected to connect and push your local repo now. If something happens or any error appear, try this command:
do the following steps:
Not the answer you’re looking for? Browse other questions tagged git repository or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.