Linux git clone repository

2.1 Git Basics — Getting a Git Repository

If you can read only one chapter to get going with Git, this is it. This chapter covers every basic command you need to do the vast majority of the things you’ll eventually spend your time doing with Git. By the end of the chapter, you should be able to configure and initialize a repository, begin and stop tracking files, and stage and commit changes. We’ll also show you how to set up Git to ignore certain files and file patterns, how to undo mistakes quickly and easily, how to browse the history of your project and view changes between commits, and how to push and pull from remote repositories.

Getting a Git Repository

You typically obtain a Git repository in one of two ways:

  1. You can take a local directory that is currently not under version control, and turn it into a Git repository, or
  2. You can clone an existing Git repository from elsewhere.

In either case, you end up with a Git repository on your local machine, ready for work.

Initializing a Repository in an Existing Directory

If you have a project directory that is currently not under version control and you want to start controlling it with Git, you first need to go to that project’s directory. If you’ve never done this, it looks a little different depending on which system you’re running:

This creates a new subdirectory named .git that contains all of your necessary repository files — a Git repository skeleton. At this point, nothing in your project is tracked yet. See Git Internals for more information about exactly what files are contained in the .git directory you just created.

If you want to start version-controlling existing files (as opposed to an empty directory), you should probably begin tracking those files and do an initial commit. You can accomplish that with a few git add commands that specify the files you want to track, followed by a git commit :

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

We’ll go over what these commands do in just a minute. At this point, you have a Git repository with tracked files and an initial commit.

Cloning an Existing Repository

If you want to get a copy of an existing Git repository — for example, a project you’d like to contribute to — the command you need is git clone . If you’re familiar with other VCSs such as Subversion, you’ll notice that the command is «clone» and not «checkout». This is an important distinction — instead of getting just a working copy, Git receives a full copy of nearly all data that the server has. Every version of every file for the history of the project is pulled down by default when you run git clone . In fact, if your server disk gets corrupted, you can often use nearly any of the clones on any client to set the server back to the state it was in when it was cloned (you may lose some server-side hooks and such, but all the versioned data would be there — see Getting Git on a Server for more details).

Читайте также:  Узнать версию линукс mint

You clone a repository with git clone . For example, if you want to clone the Git linkable library called libgit2 , you can do so like this:

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

That creates a directory named libgit2 , initializes a .git directory inside it, pulls down all the data for that repository, and checks out a working copy of the latest version. If you go into the new libgit2 directory that was just created, you’ll see the project files in there, ready to be worked on or used.

If you want to clone the repository into a directory named something other than libgit2 , you can specify the new directory name as an additional argument:

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

That command does the same thing as the previous one, but the target directory is called mylibgit .

Git has a number of different transfer protocols you can use. The previous example uses the https:// protocol, but you may also see git:// or user@server:path/to/repo.git , which uses the SSH transfer protocol. Getting Git on a Server will introduce all of the available options the server can set up to access your Git repository and the pros and cons of each.

Источник

Cloning a repository

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, or to a codespace, 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, or to a remote virtual machine when you create a codespace. For more information about cloning to a codespace, see «Creating a codespace for 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.

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.

Читайте также:  Linux curl keep alive

Cloning a repository

  1. On GitHub.com, navigate to the main page of the repository.
  2. Above the list of files, click

Screenshot of the list of files on the landing page of a repository. The

Code.

    To clone the repository using HTTPS, under «HTTPS», click

Screenshot of the

.

git clone https://github.com/YOUR-USERNAME/YOUR-REPOSITORY
$ 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 learn more about GitHub CLI, see «About GitHub CLI.»

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.

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

Screenshot of the list of files on the landing page of a repository. The

Code.

Screenshot of the

Open with 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

Screenshot of the quick setup instructions for an empty repository. To the right of the HTTPS URL for the repository, a copy icon is outlined in dark orange.

.

Alternatively, to clone your repository in Desktop, click

Screenshot of the quick setup instructions for an empty repository. A button, labeled with a download icon and

Set up in Desktop and follow the prompts to complete the clone.

git clone https://github.com/YOUR-USERNAME/YOUR-REPOSITORY
$ 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 «Troubleshooting cloning errors.»
  • You have permission to access the repository you want to clone. For more information, see «Troubleshooting cloning errors.»
  • The default branch you want to clone still exists. For more information, see «Troubleshooting cloning errors.»

Further reading

Источник

2.1 Основы Git — Создание Git-репозитория

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

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

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

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

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

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

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

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

Эта команда создаёт в текущем каталоге новый подкаталог с именем .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 . Например, если вы хотите клонировать библиотеку 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 репозиторию, а также рассмотрим их достоинства и недостатки.

Источник

Оцените статью
Adblock
detector