Git clone в текущую папку windows

When the repository to clone from is on a local machine, this flag bypasses the normal "Git aware" transport mechanism and clones the repository by making a copy of HEAD and everything under objects and refs directories. The files under .git/objects/ directory are hardlinked to save space when possible.
-l
—local

When the repository to clone from is on a local machine,
this flag bypasses the normal «Git aware» transport
mechanism and clones the repository by making a copy of
HEAD and everything under objects and refs directories.
The files under .git/objects/ directory are hardlinked
to save space when possible.

If the repository is specified as a local path (e.g., /path/to/repo),
this is the default, and —local is essentially a no-op. If the
repository is specified as a URL, then this flag is ignored (and we
never use the local optimizations). Specifying --no-local will
override the default when /path/to/repo is given, using the regular
Git transport instead.

NOTE: this operation can race with concurrent modification to the
source repository, similar to running cp -r src dst while modifying
src.

—no-hardlinks

Force the cloning process from a repository on a local
filesystem to copy the files under the .git/objects
directory instead of using hardlinks. This may be desirable
if you are trying to make a back-up of your repository.

-s
—shared

When the repository to clone is on the local machine,
instead of using hard links, automatically setup
.git/objects/info/alternates to share the objects
with the source repository. The resulting repository
starts out without any object of its own.

NOTE: this is a possibly dangerous operation; do not use
it unless you understand what it does. If you clone your
repository using this option and then delete branches (or use any
other Git command that makes any existing commit unreferenced) in the
source repository, some objects may become unreferenced (or dangling).
These objects may be removed by normal Git operations (such as git commit)
which automatically call git maintenance run --auto. (See
git-maintenance[1].) If these objects are removed and were referenced
by the cloned repository, then the cloned repository will become corrupt.

Note that running git repack without the --local option in a repository
cloned with --shared will copy objects from the source repository into a pack
in the cloned repository, removing the disk space savings of clone --shared.
It is safe, however, to run git gc, which uses the --local option by
default.

If you want to break the dependency of a repository cloned with --shared on
its source repository, you can simply run git repack -a to copy all
objects from the source repository into a pack in the cloned repository.

—reference[-if-able] <repository>

If the reference repository is on the local machine,
automatically setup .git/objects/info/alternates to
obtain objects from the reference repository. Using
an already existing repository as an alternate will
require fewer objects to be copied from the repository
being cloned, reducing network and local storage costs.
When using the --reference-if-able, a non existing
directory is skipped with a warning instead of aborting
the clone.

NOTE: see the NOTE for the --shared option, and also the
--dissociate option.

—dissociate

Borrow the objects from reference repositories specified
with the --reference options only to reduce network
transfer, and stop borrowing from them after a clone is made
by making necessary local copies of borrowed objects. This
option can also be used when cloning locally from a
repository that already borrows objects from another
repository—​the new repository will borrow objects from the
same repository, and this option can be used to stop the
borrowing.

-q
—quiet

Operate quietly. Progress is not reported to the standard
error stream.

-v
—verbose

Run verbosely. Does not affect the reporting of progress status
to the standard error stream.

—progress

Progress status is reported on the standard error stream
by default when it is attached to a terminal, unless --quiet
is specified. This flag forces progress status even if the
standard error stream is not directed to a terminal.

—server-option=<option>

Transmit the given string to the server when communicating using
protocol version 2. The given string must not contain a NUL or LF
character. The server’s handling of server options, including
unknown ones, is server-specific.
When multiple --server-option=<option> are given, they are all
sent to the other side in the order listed on the command line.

-n
—no-checkout

No checkout of HEAD is performed after the clone is complete.

—[no-]reject-shallow

Fail if the source repository is a shallow repository.
The clone.rejectShallow configuration variable can be used to
specify the default.

—bare

Make a bare Git repository. That is, instead of
creating <directory> and placing the administrative
files in <directory>/.git, make the <directory>
itself the $GIT_DIR. This obviously implies the --no-checkout
because there is nowhere to check out the working tree.
Also the branch heads at the remote are copied directly
to corresponding local branch heads, without mapping
them to refs/remotes/origin/. When this option is
used, neither remote-tracking branches nor the related
configuration variables are created.

—sparse

Employ a sparse-checkout, with only files in the toplevel
directory initially being present. The
git-sparse-checkout[1] command can be used to grow the
working directory as needed.

—filter=<filter-spec>

Use the partial clone feature and request that the server sends
a subset of reachable objects according to a given object filter.
When using --filter, the supplied <filter-spec> is used for
the partial clone filter. For example, --filter=blob:none will
filter out all blobs (file contents) until needed by Git. Also,
--filter=blob:limit=<size> will filter out all blobs of size
at least <size>. For more details on filter specifications, see
the --filter option in git-rev-list[1].

—also-filter-submodules

Also apply the partial clone filter to any submodules in the repository.
Requires --filter and --recurse-submodules. This can be turned on by
default by setting the clone.filterSubmodules config option.

—mirror

Set up a mirror of the source repository. This implies --bare.
Compared to --bare, --mirror not only maps local branches of the
source to local branches of the target, it maps all refs (including
remote-tracking branches, notes etc.) and sets up a refspec configuration such
that all these refs are overwritten by a git remote update in the
target repository.

-o <name>
—origin <name>

Instead of using the remote name origin to keep track of the upstream
repository, use <name>. Overrides clone.defaultRemoteName from the
config.

-b <name>
—branch <name>

Instead of pointing the newly created HEAD to the branch pointed
to by the cloned repository’s HEAD, point to <name> branch
instead. In a non-bare repository, this is the branch that will
be checked out.
--branch can also take tags and detaches the HEAD at that commit
in the resulting repository.

-u <upload-pack>
—upload-pack <upload-pack>

When given, and the repository to clone from is accessed
via ssh, this specifies a non-default path for the command
run on the other end.

—template=<template-directory>

Specify the directory from which templates will be used;
(See the «TEMPLATE DIRECTORY» section of git-init[1].)

-c <key>=<value>
—config <key>=<value>

Set a configuration variable in the newly-created repository;
this takes effect immediately after the repository is
initialized, but before the remote history is fetched or any
files checked out. The key is in the same format as expected by
git-config[1] (e.g., core.eol=true). If multiple
values are given for the same key, each value will be written to
the config file. This makes it safe, for example, to add
additional fetch refspecs to the origin remote.

Due to limitations of the current implementation, some configuration
variables do not take effect until after the initial fetch and checkout.
Configuration variables known to not take effect are:
remote.<name>.mirror and remote.<name>.tagOpt. Use the
corresponding --mirror and --no-tags options instead.

—depth <depth>

Create a shallow clone with a history truncated to the
specified number of commits. Implies --single-branch unless
--no-single-branch is given to fetch the histories near the
tips of all branches. If you want to clone submodules shallowly,
also pass --shallow-submodules.

—shallow-since=<date>

Create a shallow clone with a history after the specified time.

—shallow-exclude=<revision>

Create a shallow clone with a history, excluding commits
reachable from a specified remote branch or tag. This option
can be specified multiple times.

—[no-]single-branch

Clone only the history leading to the tip of a single branch,
either specified by the --branch option or the primary
branch remote’s HEAD points at.
Further fetches into the resulting repository will only update the
remote-tracking branch for the branch this option was used for the
initial cloning. If the HEAD at the remote did not point at any
branch when --single-branch clone was made, no remote-tracking
branch is created.

—no-tags

Don’t clone any tags, and set
remote.<remote>.tagOpt=--no-tags in the config, ensuring
that future git pull and git fetch operations won’t follow
any tags. Subsequent explicit tag fetches will still work,
(see git-fetch[1]).

Can be used in conjunction with --single-branch to clone and
maintain a branch with no references other than a single cloned
branch. This is useful e.g. to maintain minimal clones of the default
branch of some repository for search indexing.

—recurse-submodules[=<pathspec>]

After the clone is created, initialize and clone submodules
within based on the provided pathspec. If no pathspec is
provided, all submodules are initialized and cloned.
This option can be given multiple times for pathspecs consisting
of multiple entries. The resulting clone has submodule.active set to
the provided pathspec, or «.» (meaning all submodules) if no
pathspec is provided.

Submodules are initialized and cloned using their default settings. This is
equivalent to running
git submodule update --init --recursive <pathspec> immediately after
the clone is finished. This option is ignored if the cloned repository does
not have a worktree/checkout (i.e. if any of --no-checkout/-n, --bare,
or --mirror is given)

—[no-]shallow-submodules

All submodules which are cloned will be shallow with a depth of 1.

—[no-]remote-submodules

All submodules which are cloned will use the status of the submodule’s
remote-tracking branch to update the submodule, rather than the
superproject’s recorded SHA-1. Equivalent to passing --remote to
git submodule update.

—separate-git-dir=<git-dir>

Instead of placing the cloned repository where it is supposed
to be, place the cloned repository at the specified directory,
then make a filesystem-agnostic Git symbolic link to there.
The result is Git repository can be separated from working
tree.

-j <n>
—jobs <n>

The number of submodules fetched at the same time.
Defaults to the submodule.fetchJobs option.

<repository>

The (possibly remote) repository to clone from. See the
GIT URLS section below for more information on specifying
repositories.

<directory>

The name of a new directory to clone into. The «humanish»
part of the source repository is used if no directory is
explicitly given (repo for /path/to/repo.git and foo
for host.xz:foo/.git). Cloning into an existing directory
is only allowed if the directory is empty.

—bundle-uri=<uri>

Before fetching from the remote, fetch a bundle from the given
<uri> and unbundle the data into the local repository. The refs
in the bundle will be stored under the hidden refs/bundle/*
namespace. This option is incompatible with --depth,
--shallow-since, and --shallow-exclude.

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

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, прочитав всего одну главу, то эта глава — то, что вам нужно.
Здесь рассмотрены все базовые команды, необходимые вам для решения подавляющего большинства задач, возникающих при работе с Git.
После прочтения этой главы вы научитесь настраивать и инициализировать репозиторий, начинать и прекращать контроль версий файлов, а также подготавливать и фиксировать изменения.
Мы также продемонстрируем вам, как настроить в Git игнорирование отдельных файлов или их групп, как быстро и просто отменить ошибочные изменения, как просмотреть историю вашего проекта и изменения между отдельными коммитами (commit), а также как отправлять (push) и получать (pull) изменения в/из удалённого (remote) репозитория.

Создание Git-репозитория

Обычно вы получаете репозиторий Git одним из двух способов:

  1. Вы можете взять локальный каталог, который в настоящее время не находится под версионным контролем, и превратить его в репозиторий Git, либо

  2. Вы можете клонировать существующий репозиторий Git из любого места.

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

Создание репозитория в существующем каталоге

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

для Linux:

$ cd /home/user/my_project

для macOS:

$ cd /Users/user/my_project

для Windows:

$ cd C:/Users/user/my_project

а затем выполните команду:

Эта команда создаёт в текущем каталоге новый подкаталог с именем .git, содержащий все необходимые файлы репозитория — структуру Git репозитория.
На этом этапе ваш проект ещё не находится под версионным контролем.
Подробное описание файлов, содержащихся в только что созданном вами каталоге .git, приведено в главе Git изнутри

Если вы хотите добавить под версионный контроль существующие файлы (в отличие от пустого каталога), вам стоит добавить их в индекс и осуществить первый коммит изменений.
Добиться этого вы сможете запустив команду git add несколько раз, указав индексируемые файлы, а затем выполнив git commit:

$ git add *.c
$ git add LICENSE
$ git commit -m 'Initial project version'

Мы разберем, что делают эти команды чуть позже.
Теперь у вас есть Git-репозиторий с отслеживаемыми файлами и начальным коммитом.

Клонирование существующего репозитория

Для получения копии существующего Git-репозитория, например, проекта, в который вы хотите внести свой вклад, необходимо использовать команду git clone.
Если вы знакомы с другими системами контроля версий, такими как Subversion, то заметите, что команда называется «clone», а не «checkout».
Это важное различие — вместо того, чтобы просто получить рабочую копию, Git получает копию практически всех данных, которые есть на сервере.
При выполнении git clone с сервера забирается (pulled) каждая версия каждого файла из истории проекта.
Фактически, если серверный диск выйдет из строя, вы можете использовать любой из клонов на любом из клиентов, для того, чтобы вернуть сервер в то состояние, в котором он находился в момент клонирования (вы можете потерять часть серверных хуков (server-side hooks) и т. п., но все данные, помещённые под версионный контроль, будут сохранены, подробнее об этом смотрите в разделе Установка Git на сервер главы 4).

Клонирование репозитория осуществляется командой git clone <url>.
Например, если вы хотите клонировать библиотеку libgit2, вы можете сделать это следующим образом:

$ git clone https://github.com/libgit2/libgit2

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

$ git clone https://github.com/libgit2/libgit2 mylibgit

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

В Git реализовано несколько транспортных протоколов, которые вы можете использовать.
В предыдущем примере использовался протокол https://, вы также можете встретить git:// или user@server:path/to/repo.git, использующий протокол передачи SSH.
В разделе Установка Git на сервер главы 4 мы познакомимся со всеми доступными вариантами конфигурации сервера для обеспечения доступа к вашему Git репозиторию, а также рассмотрим их достоинства и недостатки.

Урок, в котором мы познакомимся с репозиториями 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. Форки

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

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

The most common way to clone git repository is to enter in the terminal command that
looks like something like this:

git clone https://github.com/bessarabov/my_project.git

This command will create the directory «my_project» in the current directory and it will clone
repo to that directory. Here is an example:

$ pwd
/Users/bessarabov
$ git clone https://github.com/bessarabov/my_project.git
Cloning into 'my_project'...
remote: Enumerating objects: 3, done.
remote: Counting objects: 100% (3/3), done.
remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (3/3), done.
$ ls -1a my_project/
.
..
.git
README.md
$

Command «pwd» prints the directory where you are now. The command «git clone …» does the clone.
And with «ls» command we check that there is a hidden «.git» directory that stores all the history
and other meta information and there is a «README.md» file.

Specify directory to clone to

Sometimes you need to place git repository in some other directory. Here is an example:

$ pwd
/Users/bessarabov
$ git clone https://github.com/bessarabov/my_project.git project
Cloning into 'project'...
remote: Enumerating objects: 3, done.
remote: Counting objects: 100% (3/3), done.
remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (3/3), done.
$ ls -1a project
.
..
.git
README.md
$

As you can see here I used «git clone» command with two parameters:

  • the first paramter is the url to the repo
  • the second paramter is the directory where to clone repo

Clone to the current directory

And sometimes you need to clone the git repo to the current directory. To specify
the current directory the symbol dot is used. So to clone repo to the current
directory you need to specify two parameters to git clone:

  • the url of the repo
  • just one symbol — dot — «.» — it means current directory

Here is an example:

$ mkdir the_project
$ cd the_project/
$ pwd
/Users/bessarabov/the_project
git clone https://github.com/bessarabov/my_project.git .
Cloning into '.'...
remote: Enumerating objects: 3, done.
remote: Counting objects: 100% (3/3), done.
remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (3/3), done.
$ ls -1a
.
..
.git
README.md
$

Here I have created a new directory with the name «the_project», then I’ve entered it
with «cd» command and did the clone with the command «git clone url .». The dot in
this command is what makes git clone to the directory where I’m now.

Error «fatal: destination path ‘.’ already exists and is not an empty directory»

Sometimes you can see error message:

$ git clone https://github.com/bessarabov/my_project.git .
fatal: destination path '.' already exists and is not an empty directory.

It means exactly what it it written in this message. You are trying to checkout
repo to the directory that has some files in it. With the command «ls» you can check
what files are in the current directory. It is also possible that there are some
hidden files, so it is better to use «-a» option to make «ls» show all files
including hidden:

$ ls -1a
.
..
.git
README.md

The «ls» command shows that git is right. The directory is not empty. There is a
directory .git and a file README.md. You can permanent delete that files with
the command «rm» (but do it only if you don’t need those files, you will not
be able to «undelete» them):

$ rm -rf .git README.md

After that the «git clone» will succeed:

$ git clone https://github.com/bessarabov/my_project.git .
Cloning into '.'...
remote: Enumerating objects: 3, done.
remote: Counting objects: 100% (3/3), done.
remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (3/3), done.
$

Recap

  • When you use «git clone url» the directory will be automatically created
  • You can specify what directory to create with the command «git clone url dir»
  • If you need to clone to the current directory you need to run command «git clone url .»

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

Стандартный подход к клонированию заключается в том, что репозиторий использует git-clone команда. Но когда вы просто клонируете репозиторий с git clone <repository>, он создает новый каталог с именем репозитория по текущему пути в файловой системе и клонирует репозиторий внутри него.

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

$ git clone <repository> <path>

Здесь, <path> это путь к каталогу для клонирования. Это показано ниже, где клонирование выполняется в существующий локальный каталог.

git clone directory

 
Если вы хотите клонировать репозиторий git в текущий каталог, вы можете сделать следующее:

$ git clone <repository> .

Вот, точка (.) представляет текущий каталог.

git clone .

 
В качестве альтернативы вы можете использовать git [-C ] возможность указать корневой каталог. Это работает, поскольку git возьмет на себя <path> как текущий рабочий каталог.

$ git -C <path> clone <repository>

Обратите внимание, что это создает новый каталог с именем репозитория в указанном каталоге и клонирует репозиторий внутри него, как показано ниже:

git -C directory clone

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

git error – not an empty directory

 
Если место назначения не пусто, вы можете сделать так:

# create and initialize an empty repository
$ git init

# add a remote named origin for the repository at <repository>
$ git remote add origin <repository>

# do a git-fetch
$ git fetch

# check out the master branch
$ git checkout master

Этот подход демонстрируется ниже:

git fetch

Это все о клонировании репозитория Git в определенную папку.

Спасибо за чтение.

Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.

Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂

ubuntu

  • Ubuntu

  • Git

  • Bitbucket

Как в git клонировать репозиторий в текущую папку, т.е. без создания папки с именем репозитория?

Пробовал вот так: git clone https://user@bitbucket.org/user/rep.git .
Не получается. Может, есть какой-нибудь способ?


  • Вопрос задан

    более трёх лет назад

  • 56637 просмотров



4

комментария

Пригласить эксперта


Ответы на вопрос 6

Whitemaster

ваша команда верна, но она может не работать, если директория не пуста, git не позволяет клонировать в непустую директорию


Комментировать

ripdamage

Не может быть, чтобы не получалось! Точку же ставите?

  • Точку ставлю,но при этом выводится сообщение cloning into ‘ . ‘ … и все.А если убрать точку,то все идет резво,то бишь создается в текущей папке новая папка с названием репозитория и все клонируется туда

Точка ставится через пробел, и в директории ничего не должно быть.


Комментировать

У меня вопрос:
Хочу клонировать репозиторий, ввожу логин и пароль от гитхаба, а в ответ repository not found.
Что я делаю не так?


Комментировать


Похожие вопросы


  • Показать ещё
    Загружается…

04 февр. 2023, в 15:56

2500 руб./за проект

04 февр. 2023, в 15:46

200 руб./за проект

04 февр. 2023, в 15:45

200000 руб./за проект

Минуточку внимания

Понравилась статья? Поделить с друзьями:
  • Git change password for remote repository windows
  • Global protect vpn windows 10 скачать
  • Ginzzu gr 116b драйвер windows 10
  • Gimp скачать бесплатно на русском языке для windows 7 через торрент
  • Gimp скачать бесплатно на русском языке для windows 10 64 bit