-
-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.If the repository’s
$GIT_DIR/objects
has symbolic links or is a
symbolic link, the clone will fail. This is a security measure to
prevent the unintentional copying of files by dereferencing the symbolic
links.This option does not work with repositories owned by other users for security
reasons, and--no-local
must be specified for the clone to succeed.NOTE: this operation can race with concurrent modification to the
source repository, similar to runningcp -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 asgit commit
)
which automatically callgit 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 ofclone --shared
.
It is safe, however, to rungit 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 rungit 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.
When no--server-option=
<option> is given from the command
line, the values of configuration variableremote.<name>.serverOption
are used instead. -
-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.
Theclone.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 torefs/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 theclone.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 agit 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>. Overridesclone.defaultRemoteName
from the
config. -
-b
<name> -
--branch
<name> -
Instead of pointing the newly created
HEAD
to the branch pointed
to by the cloned repository’sHEAD
, 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 theHEAD
at that commit
in the resulting repository. -
--revision=<rev>
-
Create a new repository, and fetch the history leading to the given
revision <rev> (and nothing else), without making any remote-tracking
branch, and without making any local branch, and detachHEAD
to
<rev>. The argument can be a ref name (e.g.refs/heads/main
or
refs/tags/v1.0
) that peels down to a commit, or a hexadecimal object
name.
This option is incompatible with--branch
and--mirror
. -
-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
andremote.<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=<ref>
-
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’sHEAD
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 theHEAD
at the remote did not point at any
branch when--single-branch
clone was made, no remote-tracking
branch is created. -
--[no-]tags
-
Control whether or not tags will be cloned. When
--no-tags
is
given, the option will be become permanent by setting the
remote.<remote>.tagOpt=--no-tags
configuration. This ensures that
futuregit pull
andgit fetch
won’t follow any tags. Subsequent
explicit tag fetches will still work (see git-fetch[1]).By default, tags are cloned and passing
--tags
is thus typically a
no-op, unless it cancels out a previous--no-tags
.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 hassubmodule.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. -
--ref-format=<ref-format>
-
Specify the given ref storage format for the repository. The valid values are:
-
files
for loose files with packed-refs. This is the default. -
reftable
for the reftable format. This format is experimental and its
internals are subject to change.
-
-
-j
<n> -
--jobs
<n> -
The number of submodules fetched at the same time.
Defaults to thesubmodule.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
andfoo
forhost.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 hiddenrefs/bundle/*
namespace. This option is incompatible with--depth
,
--shallow-since
, and--shallow-exclude
.
Как в git клонировать репозиторий в текущую папку, т.е. без создания папки с именем репозитория?
Пробовал вот так: git clone https://user@bitbucket.org/user/rep.git .
Не получается. Может, есть какой-нибудь способ?
-
Вопрос задан
-
63960 просмотров
Пригласить эксперта
ваша команда верна, но она может не работать, если директория не пуста, git не позволяет клонировать в непустую директорию
Не может быть, чтобы не получалось! Точку же ставите?
Точка ставится через пробел, и в директории ничего не должно быть.
У меня вопрос:
Хочу клонировать репозиторий, ввожу логин и пароль от гитхаба, а в ответ repository not found.
Что я делаю не так?
Войдите, чтобы написать ответ
-
Показать ещё
Загружается…
Минуточку внимания
To clone a Git repository into the current directory without creating an additional subdirectory, use the following command:
git clone <repository-url> .
What is Git Clone?
Definition of Git Clone
The `git clone` command is a fundamental operation in Git that allows users to create a complete local copy of a remote repository. When you clone a repository, you essentially bring down not just the latest snapshot of the files but the entire history of commits, branches, and tags, enabling you to work offline and make contributions seamlessly.
Why Clone a Repository?
Cloning a repository provides several benefits:
- Access to the entire project history: You can view the complete commit history, which is essential for understanding project evolution.
- Ability to work offline: Once cloned, you can work on the project without an internet connection and commit your changes locally.
- Contribution to open-source projects: Many open-source repositories are designed to be easily cloned, allowing you to contribute by making changes and pushing them back to the source.
git Clone Subdirectory: Your Quick Guide to Mastery
Preparing to Clone a Repository
Prerequisites
Before you can effectively clone a repository, ensure that Git is installed on your system. This can be done by running the command:
git --version
If Git is not installed, follow the installation instructions specific to your operating system (Windows, macOS, Linux).
Identifying the Repository URL
For successful cloning, you must have the correct URL of the repository you intend to clone. There are two main types of URLs:
- HTTPS URL: This is a common method for accessing public repositories, e.g., `https://github.com/user/repo.git`.
- SSH URL: Preferred for private repositories, it allows for a secure connection, e.g., `git@github.com:user/repo.git`.
You can find the URL typically on the repository’s page in platforms like GitHub, GitLab, or Bitbucket.
Git Clone: Specify Directory Like a Pro
Cloning into the Current Directory
Basic Git Clone Command
To clone a repository under default conditions, use the command:
git clone <repository-url>
Running this command will create a new directory named after the repository in your current location, populating it with the repository’s contents.
Cloning into Current Directory: Using the Current Directory as the Target
Syntax and Example
To clone a repository directly into your current directory, you can use the following command:
git clone <repository-url> .
Here, the dot (`.`) specifies that you want to clone the repository into the current working directory instead of creating a new one.
Explanation of the Command
Using a dot as the target has important implications:
- No new directory is created: The contents of the repository are placed directly into the current directory, which is particularly useful for projects that need to be merged into an existing structure.
Example in Action
- Open your terminal or command prompt.
- Navigate to the desired directory using:
cd path/to/your/directory
- Execute the git clone command with a sample repository, like so:
git clone https://github.com/user/repo.git .
- After cloning, you can type `ls` (Linux/macOS) or `dir` (Windows) to view the newly downloaded files without an additional folder.
Important Considerations
Avoiding Common Pitfalls
While cloning into the current directory is incredibly useful, it does carry some risks. If files with the same names already exist in that directory, Git will not overwrite them automatically. It’s essential to either ensure that the directory is empty or to back up important files beforehand to avoid accidental data loss.
Handling File Conflicts
If you run the clone command in a directory that already contains files, Git will notify you of a conflict, and the cloning process will be aborted. You’ll need to address any pre-existing files, which may involve renaming them or removing them if they are no longer needed before retrying the clone.
Mastering Git Clone Directory: Quick Guide to Cloning
Enhancing Your Cloning Experience
Cloning with Depth Options
Sometimes, you may only need the latest changes without the entire history. In such cases, you can use the `—depth` option to perform a shallow clone, which significantly decreases the amount of data downloaded:
git clone --depth 1 <repository-url> .
This command could be especially useful in large repositories where your focus is strictly on the latest developments.
Cloning Specific Branches or Tags
If you only want to clone a specific branch or tag from a repository without the need for the entire project history, you can specify the branch using:
git clone -b <branch-name> <repository-url> .
This is particularly advantageous when working on a specific feature or version of a project, streamlining the cloning process and keeping local storage to a minimum.
Git Clone Without History: A Quick Guide to Efficient Cloning
Conclusion
Cloning repositories is a critical skill for anyone looking to work efficiently with Git. By mastering the `git clone into current directory` command, you can enhance your workflow, streamline your projects, and collaborate more effectively.
Mastering Git Clone Repository: A Quick Guide
FAQs
What should I do if I see an error when cloning?
Common errors might occur due to permission issues or invalid URLs. Ensure that you have access to the repository and double-check the URL for typos.
Can I update my cloned repository?
Yes! Once you have cloned a repository, you can pull updates using the command:
git pull
This will synchronize your local copy with the latest changes from the remote repository.
Is it possible to undo a clone?
If you decide you no longer need the cloned repository, simply delete the directory you created during the clone. Be cautious, as this action is irreversible and will permanently delete all cloned files.
Git Include Only One Directory: A Simple Guide
Additional Resources
For further reading, you may refer to the official Git documentation. Additionally, explore various Git GUI tools that can facilitate repository management and enhance your overall experience.
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 на первое время.
Первоначальная настройка Git
Работа с любой программой всегда начинается с её настройки. Git можно настроить один раз и менять что-то только по мере необходимости.
Установка имени пользователя, от которого будут идти коммиты.
Установка адреса электронной почты. Обратите внимание, что адрес должен совпадать с тем, на который зарегистрирован аккаунт в Гитхабе.
Установка текстового редактора, в котором будут открываться файлы для решения конфликтов.
С помощью команды git config --list
можно посмотреть список всех установленных настроек.
Клонирование репозитория
Для клонирования репозитория нужно ввести команду git clone
и указать его адрес. Репозиторий клонируется в текущую выбранную папку в консоли.
Работа с изменениями
Любая работа с изменениями начинается с получения последней версии удалённого репозитория. Получить последнюю версию можно с помощью команды git pull
. Будьте внимательны, вызов этой команды сотрёт все незафиксированные изменения.
После внесения любых изменений в проект можно посмотреть статус файлов с помощью команды git status
. Она покажет файлы, в которых были произведены изменения, удалённые и новые, требующие добавления.
Чтобы добавить отслеживание новых файлов, необходимо использовать команду git add <filename> <filename>
для добавления нескольких файлов по имени.
В случае если у вас много файлов для добавления, можно воспользоваться командой git add .
, которая добавляет отслеживание для всех новых файлов из текущей директории. А команда git add -A
добавляет ещё и удалённые файлы, не только из текущей директории, но и из всего локального репозитория.
Помимо добавления файлов, их также необходимо удалять. Для этого существует команда git rm <filename> <filename>
, которая удаляет файлы по их имени.
После того как добавлены все новые и удалены старые файлы, можно делать фиксацию изменений. Фиксация изменений или коммит, очень важна, так как до выполнения этой команды ваши локальные изменения никуда не запишутся. Чтобы добавить коммит, необходимо ввести команду git commit -m "Комментарий к коммиту"
.
Стоит отметить, что необходимо правильно разбивать изменения на коммиты и давать полные комментарии к коммитам. Подробнее на эту тему можно почитать здесь.
Если вы внесли изменения и хотите быстро их отменить, то воспользуйтесь командой git reset
, которая отменяет все незафиксированные изменения.
По умолчанию, эта команда удаляет только из индекса. А команда git reset --hard
безвозвратно удаляет незафиксированные текущие изменения из локального репозитория и из индекса.
Поскольку все вышеописанные действия производятся в локальной копии репозитория, эту копию необходимо отправить на сервер, чтобы другие участники процесса смогли получить актуальную версию. Для этого есть команда git push
, которая отправляет все зафиксированные изменения на удалённый репозиторий.
Работа с ветками
Работая с Git, приходится постоянно создавать и перемещаться по веткам.
Команда git checkout -b branch-name
создаст ветку с указанным именем и автоматически переключится на неё.
После создания ветку можно отправить на сервер с помощью команды git push origin branch-name
.
Аналогично можно забрать себе на компьютер ветку с удалённого репозитория командой git checkout origin/branch-name -b branch-name
.
Чтобы не хранить названия веток в памяти или не искать названия веток, существуют две специальные команды, которые позволяют посмотреть все существующие ветки локального репозитория git branch
или все существующие ветки удалённого репозитория git branch -r
.
Переключиться на любую локальную ветку можно с помощью команды git checkout branch-name
.
Прочее
После работы в репозитории могут оставаться различные ненужные, неотслеживаемые файлы и прочий мусор. Чтобы удалить всё лишнее, воспользуйтесь командой git clean -f -d
.
Больше статей
- Как склеить коммиты и зачем это нужно
- Шпаргалка по Git
- Как работать с GitHub в большой команде
«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.
ТелеграмПодкастБесплатные учебники