Как клонировать репозиторий с github в папку windows

When you create a repository on GitHub.com, it exists as a remote repository. You can clone your repository to create a local copy on your computer and sync between the two locations.

About cloning a repository

You can clone a repository from GitHub.com to your local computer to make it easier to fix merge conflicts, add or remove files, and push larger commits. When you clone a repository, you copy the repository from GitHub.com to your local machine.

Cloning a repository pulls down a full copy of all the repository data that GitHub.com has at that point in time, including all versions of every file and folder for the project. You can push your changes to the remote repository on GitHub.com, or pull other people’s changes from GitHub.com. For more information, see «Using Git».

You can clone your existing repository or clone another person’s existing repository to contribute to a project.

Cloning a repository

  1. On GitHub.com, navigate to the main page of the repository.

  2. Above the list of files, click Code.
    "Code" button

  3. Copy the URL for the repository.

    • To clone the repository using HTTPS, under «HTTPS», click .
    • To clone the repository using an SSH key, including a certificate issued by your organization’s SSH certificate authority, click SSH, then click .
    • To clone a repository using GitHub CLI, click GitHub CLI, then click .
      The clipboard icon for copying the URL to clone a repository with GitHub CLI
  4. Open TerminalTerminalGit Bash.

  5. Change the current working directory to the location where you want the cloned directory.

  6. Type git clone, and then paste the URL you copied earlier.

    $ git clone https://github.com/YOUR-USERNAME/YOUR-REPOSITORY
  7. Press Enter to create your local clone.

    $ git clone https://github.com/YOUR-USERNAME/YOUR-REPOSITORY
    > Cloning into `Spoon-Knife`...
    > remote: Counting objects: 10, done.
    > remote: Compressing objects: 100% (8/8), done.
    > remove: Total 10 (delta 1), reused 10 (delta 1)
    > Unpacking objects: 100% (10/10), done.

To clone a repository locally, use the repo clone subcommand. Replace the repository parameter with the repository name. For example, octo-org/octo-repo, monalisa/octo-repo, or octo-repo. If the OWNER/ portion of the OWNER/REPO repository argument is omitted, it defaults to the name of the authenticating user.

gh repo clone REPOSITORY

You can also use the GitHub URL to clone a repository.

gh repo clone https://github.com/PATH-TO/REPOSITORY
  1. On GitHub.com, navigate to the main page of the repository.
  2. Above the list of files, click Code.
    "Code" button
  3. Click Open with GitHub Desktop to clone and open the repository with GitHub Desktop.
    "Open with GitHub Desktop" button
  4. Follow the prompts in GitHub Desktop to complete the clone.

For more information, see «Cloning a repository from GitHub to GitHub Desktop.»

Cloning an empty repository

An empty repository contains no files. It’s often made if you don’t initialize the repository with a README when creating it.

  1. On GitHub.com, navigate to the main page of the repository.

  2. To clone your repository using the command line using HTTPS, under «Quick setup», click . To clone the repository using an SSH key, including a certificate issued by your organization’s SSH certificate authority, click SSH, then click .
    Empty repository clone URL button

    Alternatively, to clone your repository in Desktop, click Set up in Desktop and follow the prompts to complete the clone.
    Empty repository clone desktop button

  3. Open TerminalTerminalGit Bash.

  4. Change the current working directory to the location where you want the cloned directory.

  5. Type git clone, and then paste the URL you copied earlier.

    $ git clone https://github.com/YOUR-USERNAME/YOUR-REPOSITORY
  6. Press Enter to create your local clone.

    $ git clone https://github.com/YOUR-USERNAME/YOUR-REPOSITORY
    > Cloning into `Spoon-Knife`...
    > remote: Counting objects: 10, done.
    > remote: Compressing objects: 100% (8/8), done.
    > remove: Total 10 (delta 1), reused 10 (delta 1)
    > Unpacking objects: 100% (10/10), done.

Troubleshooting cloning errors

When cloning a repository it’s possible that you might encounter some errors.

If you’re unable to clone a repository, check that:

  • You can connect using HTTPS. For more information, see «HTTPS cloning errors.»
  • You have permission to access the repository you want to clone. For more information, see «Error: Repository not found.»
  • The default branch you want to clone still exists. For more information, see «Error: Remote HEAD refers to nonexistent ref, unable to checkout.»

Further reading

  • «Troubleshooting connectivity problems»

Git clone illustration

The git clone command is used to create a copy of a specific repository or branch within a repository.

Git is a distributed version control system. Maximize the advantages of a full repository on your own machine by cloning.

What Does git clone Do?

git clone https://github.com/github/training-kit.git

When you clone a repository, you don’t get one file, like you may in other centralized version control systems. By cloning with Git, you get the entire repository — all files, all branches, and all commits.

Cloning a repository is typically only done once, at the beginning of your interaction with a project. Once a repository already exists on a remote, like on GitHub, then you would clone that repository so you could interact with it locally. Once you have cloned a repository, you won’t need to clone it again to do regular development.

The ability to work with the entire repository means that all developers can work more freely. Without being limited by which files you can work on, you can work on a feature branch to make changes safely. Then, you can:

  • later use git push to share your branch with the remote repository
  • open a pull request to compare the changes with your collaborators
  • test and deploy as needed from the branch
  • merge into the main branch.

How to Use git clone

Common usages and options for git clone

  • git clone [url]: Clone (download) a repository that already exists on GitHub, including all of the files, branches, and commits.
  • git clone --mirror: Clone a repository but without the ability to edit any of the files. This includes the refs, or branches. You may want to use this if you are trying to create a secondary copy of a repository on a separate remote and you want to match all of the branches. This may occur during configuration using a new remote for your Git hosting, or when using Git during automated testing.
  • git clone --single-branch: Clone only a single branch
  • git clone --sparse: Instead of populating the working directory with all of the files in the current commit recursively, only populate the files present in the root directory. This could help with performance when cloning large repositories with many directories and sub-directories.
  • `git clone —recurse-submodules[=<pathspec]: After the clone is created, initialize and clone submodules within based on the provided pathspec. This may be a good option if you are cloning a repository that you know to have submodules, and you will be working with those submodules as dependencies in your local development.

You can see all of the many options with git clone in git-scm’s documentation.

Examples of git clone

git clone [url]

The most common usage of cloning is to simply clone a repository. This is only done once, when you begin working on a project, and would follow the syntax of git clone [url].

git clone A Branch

git clone --single-branch: By default, git clone will create remote tracking branches for all of the branches currently present in the remote which is being cloned. The only local branch that is created is the default branch.

But, maybe for some reason you would like to only get a remote tracking branch for one specific branch, or clone one branch which isn’t the default branch. Both of these things happen when you use --single-branch with git clone.

This will create a clone that only has commits included in the current line of history. This means no other branches will be cloned. You can specify a certain branch to clone, but the default branch, usually main, will be selected by default.

To clone one specific branch, use:

git clone [url] --branch [branch] --single-branch

Cloning only one branch does not add any benefits unless the repository is very large and contains binary files that slow down the performance of the repository. The recommended solution is to optimize the performance of the repository before relying on single branch cloning strategies.

git clone With SSH

Depending on how you authenticate with the remote server, you may choose to clone using SSH.

If you choose to clone with SSH, you would use a specific SSH path for the repository instead of a URL. Typically, developers are authenticated with SSH from the machine level. This means that you would probably clone with HTTPS or with SSH — not a mix of both for your repositories.

Related Terms

  • git branch: This shows the existing branches in your local repository. You can also use git branch [banch-name] to create a branch from your current location, or git branch --all to see all branches, both the local ones on your machine, and the remote tracking branches stored from the last git pull or git fetch from the remote.
  • git pull: Updates your current local working branch with all new commits from the corresponding remote branch on GitHub. git pull is a combination of git fetch and git merge.
  • git push: Uploads all local branch commits to the remote.
  • git remote -v: Show the associated remote repositories and their stored name, like origin.

Contribute to this article on GitHub.

Get started with git and GitHub

Review code, manage projects, and build software alongside 40 million developers.

Sign up for GitHub

Sign in

Клонирование репозитория с GitHub через Git на Windows

27 Сен

Репозиторий — это место, где хранятся некие данные (файлы), можно сказать, что это просто директория или же папка.

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

Удалённый репозиторий — это место в неком облачном хранилище, к которой Вы имеете доступ, в котором хранятся некие данные (файлы).

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

Примечание: на операционной системе Windows (в некоторых версиях) периодически возникают проблемы с «правами доступа». Чтобы не править настройки (каждый случай, можно сказать, индивидуален) будем использовать вариант, который работает во многих случаях. 

Примечание: если Вы подключены к интернету с помощью прокси — могут возникнуть проблемы.

  1. Перейдите в папку «Мои документы»;
  2. Создайте папку с названием «Git». Имя можете сделать своё (лучше используйте латиницу), в примере будет рассматриваться имя папки «Git»;
  3. Кликните правой кнопкой мыши в папке «Git» и выберите «Git Bash Here». Откроется консоль;
  4.  Введите команду

    git clone «https://github.com/DaemonNikolay/trainingRepository»

  5. Пойдёт процесс клонирования, он не долгий, несколько секунд;
  6. В папке, куда клонировали, появится новая папочка с именем «trainingRepository»;Клонирование репозитория с GitHub через Git на Windows

Таким не хитрым образом мы разобрались с «клонирование репозитория с GitHub через Git на Windows»!

How to change the cloning folder of a specific git? My default storage directory is here

C:UsersmyPCDocumentsGitHub

But for this one git

https://github.com/username/myproject

I want to put it in

C:somefolder

(and not like C:somefoldermyproject but all the files under C:somefolder)

How to do that? I tried git clone command line but then the git doesn’t show up in my Github for Windows client

Sorry for basic question but couldn’t google or search here any answer!

asked Dec 20, 2012 at 7:40

HP.'s user avatar

1

After you have manually cloned the repository with git clone, you can manually Add a local repository to Github for Windows (I can’t take a screenshot right now because I’m on another machine, but it should be relatively easy to find).
I honestly don’t know, though, if this will then have the full set of features (i.e. if GhfW recognizes it as a Github clone), or if it will have the reduced «regular» set for repositories in general.

As always: Try it and see! :D

answered Dec 20, 2012 at 7:42

Nevik Rehnel's user avatar

Nevik RehnelNevik Rehnel

48k6 gold badges60 silver badges50 bronze badges

1

In «GitHub for Windows» first go to Tools—>Options
Here select your folder in «default storage directory». Now in GitHub if you click on «Clone in Desktop» button then it will clone in selected folder

answered Apr 7, 2014 at 12:45

Anuj Mehta's user avatar

Anuj MehtaAnuj Mehta

1,0523 gold badges12 silver badges25 bronze badges

2

Another option that I’ve tried is to use the «Create repo» command to create an (empty) repository in the folder of your choice, and then hook it up to Github by:

  1. Opening the repository settings (click the cog on the top right, select «Repository settings…»)
  2. Copying and pasting the HTTPS clone URL from the Github page (in the right sidebar) into the field that says «Primary remote (origin)»
  3. Sync the repo with the newly attached origin. You may need to open it in shell to get it to work without errors.

Why Github doesn’t make this easier, I do not know. Two years after this question was posted, and it’s still a hassle. It’s nice to have a default storage directory, but it’s also nice to have a «Where do you want to save this?» option.

Finally, if you do clone a repo into the wrong place, and want to move it somewhere else:

  1. Open up the repo in Explorer (if you’re not sure where it is on your local file system, use the «Open in Explorer» option from the little cog icon on Github for Windows).
  2. Cut and paste the entire folder to wherever you want it to be.
  3. Go back to Github for Windows. It will now give you an error message that it cannot locate the repository. Select the «Locate» option, and find the folder’s new location yourself.

This might actually be the easiest option for getting the repo where you want it.

answered Jan 5, 2015 at 3:46

AmeliaBR's user avatar

AmeliaBRAmeliaBR

27.1k6 gold badges85 silver badges117 bronze badges

The latest GitHub desktop client (3.3.4.0) prompts for a local directory to clone the repo to. This was when cloning my own repo from github.com to local.

answered Sep 29, 2017 at 9:13

KalenGi's user avatar

KalenGiKalenGi

1,7464 gold badges25 silver badges40 bronze badges

I’ve downloaded recently GitHub for Windows and it didn’t come with option Add a local repository.

I had to clone and delete the folder in Windows Explorer.
The program gives and error for this repository and the option to locate the new folder or remove.
Locate the folder to which one that you want.

answered Jun 20, 2014 at 1:37

Andre Figueiredo's user avatar

Andre FigueiredoAndre Figueiredo

12.7k7 gold badges47 silver badges74 bronze badges

1

Just change the working directory in git bash by the cd command.
Once that is done you can check if the directory you want to download/clone your git repo pwdcommand. Now you can clone the repo into the desired folder.
As usual use git clone to clone the Repository.

Hope this helps.

answered Nov 21, 2016 at 15:06

stochastiker's user avatar

How to change the cloning folder of a specific git? My default storage directory is here

C:UsersmyPCDocumentsGitHub

But for this one git

https://github.com/username/myproject

I want to put it in

C:somefolder

(and not like C:somefoldermyproject but all the files under C:somefolder)

How to do that? I tried git clone command line but then the git doesn’t show up in my Github for Windows client

Sorry for basic question but couldn’t google or search here any answer!

asked Dec 20, 2012 at 7:40

HP.'s user avatar

1

After you have manually cloned the repository with git clone, you can manually Add a local repository to Github for Windows (I can’t take a screenshot right now because I’m on another machine, but it should be relatively easy to find).
I honestly don’t know, though, if this will then have the full set of features (i.e. if GhfW recognizes it as a Github clone), or if it will have the reduced «regular» set for repositories in general.

As always: Try it and see! :D

answered Dec 20, 2012 at 7:42

Nevik Rehnel's user avatar

Nevik RehnelNevik Rehnel

48k6 gold badges60 silver badges50 bronze badges

1

In «GitHub for Windows» first go to Tools—>Options
Here select your folder in «default storage directory». Now in GitHub if you click on «Clone in Desktop» button then it will clone in selected folder

answered Apr 7, 2014 at 12:45

Anuj Mehta's user avatar

Anuj MehtaAnuj Mehta

1,0523 gold badges12 silver badges25 bronze badges

2

Another option that I’ve tried is to use the «Create repo» command to create an (empty) repository in the folder of your choice, and then hook it up to Github by:

  1. Opening the repository settings (click the cog on the top right, select «Repository settings…»)
  2. Copying and pasting the HTTPS clone URL from the Github page (in the right sidebar) into the field that says «Primary remote (origin)»
  3. Sync the repo with the newly attached origin. You may need to open it in shell to get it to work without errors.

Why Github doesn’t make this easier, I do not know. Two years after this question was posted, and it’s still a hassle. It’s nice to have a default storage directory, but it’s also nice to have a «Where do you want to save this?» option.

Finally, if you do clone a repo into the wrong place, and want to move it somewhere else:

  1. Open up the repo in Explorer (if you’re not sure where it is on your local file system, use the «Open in Explorer» option from the little cog icon on Github for Windows).
  2. Cut and paste the entire folder to wherever you want it to be.
  3. Go back to Github for Windows. It will now give you an error message that it cannot locate the repository. Select the «Locate» option, and find the folder’s new location yourself.

This might actually be the easiest option for getting the repo where you want it.

answered Jan 5, 2015 at 3:46

AmeliaBR's user avatar

AmeliaBRAmeliaBR

27.1k6 gold badges85 silver badges117 bronze badges

The latest GitHub desktop client (3.3.4.0) prompts for a local directory to clone the repo to. This was when cloning my own repo from github.com to local.

answered Sep 29, 2017 at 9:13

KalenGi's user avatar

KalenGiKalenGi

1,7464 gold badges25 silver badges40 bronze badges

I’ve downloaded recently GitHub for Windows and it didn’t come with option Add a local repository.

I had to clone and delete the folder in Windows Explorer.
The program gives and error for this repository and the option to locate the new folder or remove.
Locate the folder to which one that you want.

answered Jun 20, 2014 at 1:37

Andre Figueiredo's user avatar

Andre FigueiredoAndre Figueiredo

12.7k7 gold badges47 silver badges74 bronze badges

1

Just change the working directory in git bash by the cd command.
Once that is done you can check if the directory you want to download/clone your git repo pwdcommand. Now you can clone the repo into the desired folder.
As usual use git clone to clone the Repository.

Hope this helps.

answered Nov 21, 2016 at 15:06

stochastiker's user avatar

Here’s how I would do it, but I have made an alias to do it for me.

$ cd ~Downloads/git; git clone https:git.foo/poo.git

There is probably a more elegant way of doing this, however I found this to be easiest for myself.

Here’s the alias I created to speed things along. I made it for zsh, but it should work just fine for bash or any other shell like fish, xyzsh, fizsh, and so on.

Edit ~/.zshrc, /.bashrc, etc. with your favorite editor (mine is Leafpad, so I would write $ leafpad ~/.zshrc).

My personal preference, however, is to make a zsh plugin to keep track of all my aliases. You can create a personal plugin for oh-my-zsh by running these commands:

$ cd ~/.oh-my-zsh/
$ cd plugins/
$ mkdir your-aliases-folder-name; cd your-aliases-folder-name
     # In my case '~/.oh-my-zsh/plugins/ev-aliases/ev-aliases'
$ leafpad your-zsh-aliases.plugin.zsh
     # Again, in my case 'ev-aliases.plugin.zsh'

Afterwards, add these lines to your newly created blank alises.plugin file:

# Git aliases
alias gc="cd ~/Downloads/git; git clone "

(From here, replace your name with mine.)

Then, in order to get the aliases to work, they (along with zsh) have to be sourced-in (or whatever it’s called). To do so, inside your custom plugin document add this:

## Ev's Aliases

#### Remember to re-source zsh after making any changes with these commands:

#### These commands should also work, assuming ev-aliases have already been sourced before:

allsource="source $ZSH/oh-my-zsh.sh ; source /home/ev/.oh-my-zsh/plugins/ev-aliases/ev-aliases.plugin.zsh; clear"
sourceall="source $ZSH/oh-my-zsh.sh ; source /home/ev/.oh-my-zsh/plugins/ev-aliases/ev-aliases.plugin.zsh"
#### 

####################################

# git aliases

alias gc="cd ~/Downloads/git; git clone "
# alias gc="git clone "
# alias gc="cd /your/git/folder/or/whatever; git clone "

####################################

Save your oh-my-zsh plugin, and run allsource. If that does not seem to work, simply run source $ZSH/oh-my-zsh.sh; source /home/ev/.oh-my-zsh/plugins/ev-aliases/ev-aliases.plugin.zsh. That will load the plugin source which will allow you to use allsource from now on.


I’m in the process of making a Git repository with all of my aliases. Please feel free to check them out here: Ev’s dot-files. Please feel free to fork and improve upon them to suit your needs.

Урок, в котором мы познакомимся с репозиториями git, научимся их создавать и клонировать, а также узнаем, зачем нужны ssh-ключи

Видеоурок. Часть 1. Практика

Все о репозиториях

  • что это такое
  • клонирование
  • публичные и приватные репозитории
  • создаем собственный репозиторий
  • Инициализация репозитория
  • Генерируем ssh-ключи

ssh-ключи

  • что это такое и зачем они нужны
  • генерируем свой ключ

Видеоурок. Часть 2

  • Что выбрать: github или bitbucket?
  • Копирование ssh-ключей

Конспект урока

Краткое содержание урока, основные инструкции для командной строки, полезные ссылки и советы.

Что такое репозиторий

Это каталог в файловой системе, где хранится информация о проекте:

  • файлы и папки проекта
  • история проекта
  • настройки проекта
  • служебная информация

Информация о репозитории хранится в скрытой папке .git в корне проекта.

Можно ли работать с git локально

Да, можно. Но при этом проект находится только на нашей машине и в случае поломки железа или случайной потери данных мы не сможем восстановить проект.

Локальный репозиторий

Это репозиторий, который хранится на нашей машине, в рабочей папке проекта. Это та самая скрытая папка .git

Удаленный репозиторий, зачем он нужен

Это репозиторий, который хранится в облаке, на сторонних сервисах, специально созданных под работу с проектами git.

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

  • выполняет роль резервной копии
  • возможность работать в команде
  • некоторые дополнительные возможности, которые предоставляет хостинг. Например, визуализация истории или возможность работать над проектом прямо в веб-интерфейсе

Что такое клонирование

Это копирование удаленного репозитория на локальную машину. Обычно это первое действие при работе с проектом.
При клонировании на нашу машину копируются файлы и папки проекта и вся его история.
То есть мы получаем доступ к истории не с момента начала нашей работы над проектом, а с самого начала проекта.

Как клонировать готовый проект

В первую очередь, нужно получить ссылку на проект. Мы можем найти ее сами или получим готовую, например, на новой работе.
Возьмем для примера репозиторий vuejs — https://github.com/vuejs/vue.git

Наберем в командной строке


    $ git clone https://github.com/vuejs/vue.git

При этом в текущем каталоге создастся папка vue, в ней окажутся все файлы проекта vue и специальная скрытая папка .git, то есть сам репозиторий, или информация о нем.

Как клонировать проект в другую папку

При клонировании по умолчанию создается папка с таким же названием, как и у репозитория. Но можно склонировать репозиторий и в другую папку вот так


    $ git clone https://github.com/vuejs/vue.git vue-new

Где vue-new — нужное название папки.

Свой удаленный репозиторий

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

Где держать репозиторий

Есть множество вариантов, самые известные — это github и bitbucket. Нужно выбирать.

github или bitbucket

На самом деле не парьтесь. У них схожий функционал, и в начале работы с git мы не заметим разницы.
bitbucket мне нравится больше из-за интерфейса, но в уроках выберем github из-за его большей популярности.

Чтобы продолжить уроки, нужно зарегистрироваться на github. Если у вас нет там аккаунта, то форму регистрации увидите сразу на главной странице — https://github.com/

Как создать репозиторий в github

После регистрации создание репозитория доступно с главной страницы github. При создании нужно указать название проекта и тип (публичный или приватный). На остальное пока не обращаем внимания.

Права на репозиторий, публичные и приватные

Есть 2 типа репозиториев:

  • публичный (public), открыт всем
  • приватный (private), доступен только определенному кругу лиц — в первую очередь, нам самим

Публичные репозитории хороши для opensource-проектов и чтобы показать в резюме. Пока нам это не нужно.

Для себя будем создавать приватные репозитории. Для этого нам понадобятся ssh-ключи.

нельзя просто так клонировать приватный репозиторий

Что такое ssh-ключи

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

ssh-ключ не имеет прямого отношения к git, но так репозитории находятся на удаленных серверах, то ssh-ключи используются для разграничения доступа к приватным репозиториям.

ssh-ключ состоит из пары ключей: публичного и приватного ключа. Это просто 2 текстовых файла:

  • /домашний-каталог/.ssh/id_rsa.pub — публичный
  • /домашний-каталог/.ssh/id_rsa — приватный

Публичный ключ передается сторонним серверам, например, github, для открытия доступа на эти сервера. Приватный ключ хранится только на нашей машине и никому не передается.
То есть когда у нас просят ssh-ключ, чтобы дать доступ на какой-нибудь сервер, мы отдаем именно публичный ключ, id_rsa.pub

Как сгенерировать ssh-ключ

ssh-ключи сами собой не появляются, но стоит проверить, возможно, они были установлены раньше. Запустим в терминале команды


    $ cd ~/.ssh
    $ ls -l

Если видим файлы id_rsa и id_rsa.pub — отлично, ключи уже есть.

Если этих файлов нет, то нужно сгенерировать ключи утилитой ssh-keygen. В Windows она устанавливается вместе с git, в Linux и MacOS при необходимости установите. В Linux, например, вот так


    $ sudo apt install ssh-keygen

После этого нужно сгенерировать пару ключей, запустив команду в терминале


    $ ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

Проверяем


    $ ls -l
    total 24
    -rw-------  1 sn8 sn8 1675 Feb 11  2017 id_rsa
    -rw-r--r--  1 sn8 sn8  392 Feb 11  2017 id_rsa.pub
    -rw-r--r--  1 sn8 sn8 5746 Oct 28 21:52 known_hosts

Появились файлы id_rsa и id_rsa.pub — значит, ключи успешно сгенерированы.

known_hosts — это файл, в котором ssh прописывает сервера, на которые мы заходим.
При первом подключении к github нужно будет разрешить доступ к github.com (напечатать yes в терминале)

Как добавить ssh-ключ в настройках github

Открываем публичный ключ id_rsa.pub и копируем его содержимое. В настройках github ищем раздел «SSH и GPG keys» — https://github.com/settings/keys.
Жмем «New SSH key», задаем название ключа, например, имя, и вставляем форму публичный ключ, прямо текстом. Все, теперь у нас есть доступ к нашим приватным репозиториям.

Два способа создания проекта

Первый, когда мы начинаем новый проект. Удобнее будет создать репозиторий на github и склонировать пустой проект на локальную машину.

Второй, когда у нас уже есть проект. Нужно зайти в папку проекта и связать его с уже существующим репозиторием на github. Это называется инициализация.

Рассмотрим оба способа.

Пустой проект

Создаем приватный репозиторий на github, назовем его first-site.
Я зарегистрировался под именем Webdevkin, моя ссылка для клонирования будет такая — git@github.com:Webdevkin/first-site.git. Ваша зависит от имени пользователя.

Идем в командную строку и запускаем


    $ git clone git@github.com:Webdevkin/first-site.git

В текущей папке получим новую папку с названием first-site — это и есть наш проект.

P.S. У вас склонировать этот репозиторий не получится — он закрытый. Создайте свой :-)

Непустой проект

Допустим, у нас на локальной машине уже есть проект second-site. Создаем в github репозиторий second-site. Заходим в папку проекта и выполняем команды


    $ git init
    $ git add .
    $ git commit -m "Initial commit"
    $ git remote add origin git@github.com:Webdevkin/second-site.git
    $ git push -u origin master

Все, можно приступать к работе над проектом. Команды add, commit и push мы разберем в следующих уроках.

Это единственный урок, в котором мы разбирались с тонкостями репозиториев. В дальнейшем будем считать, что репозиторий = проект.

Что могу посоветовать

  • github или bitbucket? Для личных проектов неважно, оба сервиса разрешают бесплатно создавать приватные репозитории. Для open source или резюме — github
  • не увлекайтесь клонированием в папку со своим названием. Есть шанс запутаться, самому или коллегам
  • не путайте публичный и приватный ключи. Отдаем вовне только публичный ключ id_rsa.pub
  • при смене рабочей машины можно не генерировать ssh-ключи заново, а скопировать их со старой машины. Тогда не придется заново прописывать новые ключи на серверах

Немного подробнее о копировании ssh-ключей

Как скопировать ssh-ключи с одной машины на другую

Хочу немного затронуть эту тему отдельно. Генерировать ключ на новой машине не обязательно. Но нужно выполнить такие действия

  • Скопировать id_rsa и id_rsa.pub со старой машины на новую
  • Посмотреть права на файлы, возможно, ключи окажутся слишком «открытыми» для записи и потребуется сменить им права доступа — sudo chmod 700 ~/.ssh/*
  • Выполнить команду ssh-add

Ссылки, которые могут пригодиться

  • github — https://github.com/
  • bitbucket — https://bitbucket.org/
  • подробнее об ssh-ключах (en) — connecting-to-github-with-ssh

На этом все. В следующем уроке мы сделаем первые изменения в проекте и начнем понимать, в чем заключается прелесть git.

Спасибо за внимание и до встречи!

Все уроки курса

  • Вводный урок
  • 1. Установка и базовая настройка git
  • 2. Создание и клонирование репозитория git
  • 3. Делаем первые изменения, git status и git diff
  • 4. Коммиты и история коммитов, git commit, git log и git show
  • 5. Подробнее об истории коммитов. Путешествие по истории
  • 6. Работа с сервером, git push и git pull
  • 7. Ветки — главная фишка git, git branch и git checkout
  • 8. Работа с ветками на сервере, git fetch
  • 9. Слияния или мерджи веток, git merge
  • 10. Конфликты и их разрешение
  • Платная часть курса. Презентация
  • * 11. Работа с gitignore и git exclude
  • * 12. Буфер обмена git, git stash
  • * 13. Копирование коммитов, git cherry-pick
  • * 14. Отмена и редактирование последнего коммита
  • * 15. Отмена произвольного коммита, git revert
  •    16. Склеивание коммитов, git rebase —interactive и git reflog
  • * 17. Зачем склеивать коммиты. Плюсы и минусы сквоша
  • * 18. Работа с git rebase. Отличия от merge
  • * 19. Что такое git push —force и как с ним работать
  • * 20. Ищем баги с помощью git, git bisect
  • * 21. Как и зачем работать с тегами git
  • * 22. Процессы: github flow и git flow
  • * 23. Псевдонимы в git
  •    24. Мердж-реквесты
  • * 25. Форки

* платные уроки

список обновляется…

Понравилась статья? Поделить с друзьями:
  • Как клонировать репозиторий git в windows
  • Как клонировать разделы жесткого диска с windows на ssd диск
  • Как клонировать программу на windows 10
  • Как клонировать приложения на пк windows
  • Как клонировать загрузочную флешку windows 10