Build git on windows

1.5 Getting Started — Installing Git

Installing Git

Before you start using Git, you have to make it available on your computer. Even if it’s already installed, it’s probably a good idea to update to the latest version. You can either install it as a package or via another installer, or download the source code and compile it yourself.

This book was written using Git version 2.8.0. Though most of the commands we use should work even in ancient versions of Git, some of them might not or might act slightly differently if you’re using an older version. Since Git is quite excellent at preserving backwards compatibility, any version after 2.8 should work just fine.

Installing on Linux

If you want to install the basic Git tools on Linux via a binary installer, you can generally do so through the package management tool that comes with your distribution. If you’re on Fedora (or any closely-related RPM-based distribution, such as RHEL or CentOS), you can use dnf :

If you’re on a Debian-based distribution, such as Ubuntu, try apt :

For more options, there are instructions for installing on several different Unix distributions on the Git website, at https://git-scm.com/download/linux.

Installing on macOS

There are several ways to install Git on a Mac. The easiest is probably to install the Xcode Command Line Tools. On Mavericks (10.9) or above you can do this simply by trying to run git from the Terminal the very first time.

If you don’t have it installed already, it will prompt you to install it.

If you want a more up to date version, you can also install it via a binary installer. A macOS Git installer is maintained and available for download at the Git website, at https://git-scm.com/download/mac.

Installing on Windows

There are also a few ways to install Git on Windows. The most official build is available for download on the Git website. Just go to https://git-scm.com/download/win and the download will start automatically. Note that this is a project called Git for Windows, which is separate from Git itself; for more information on it, go to https://gitforwindows.org.

To get an automated installation you can use the Git Chocolatey package. Note that the Chocolatey package is community maintained.

Installing from Source

Some people may instead find it useful to install Git from source, because you’ll get the most recent version. The binary installers tend to be a bit behind, though as Git has matured in recent years, this has made less of a difference.

If you do want to install Git from source, you need to have the following libraries that Git depends on: autotools, curl, zlib, openssl, expat, and libiconv. For example, if you’re on a system that has dnf (such as Fedora) or apt-get (such as a Debian-based system), you can use one of these commands to install the minimal dependencies for compiling and installing the Git binaries:

In order to be able to add the documentation in various formats (doc, html, info), these additional dependencies are required:

Users of RHEL and RHEL-derivatives like CentOS and Scientific Linux will have to enable the EPEL repository to download the docbook2X package.

If you’re using a Debian-based distribution (Debian/Ubuntu/Ubuntu-derivatives), you also need the install-info package:

Читайте также:  Удалить сохраненные учетные данные windows

If you’re using a RPM-based distribution (Fedora/RHEL/RHEL-derivatives), you also need the getopt package (which is already installed on a Debian-based distro):

Additionally, if you’re using Fedora/RHEL/RHEL-derivatives, you need to do this:

due to binary name differences.

When you have all the necessary dependencies, you can go ahead and grab the latest tagged release tarball from several places. You can get it via the kernel.org site, at https://www.kernel.org/pub/software/scm/git, or the mirror on the GitHub website, at https://github.com/git/git/releases. It’s generally a little clearer what the latest version is on the GitHub page, but the kernel.org page also has release signatures if you want to verify your download.

Then, compile and install:

After this is done, you can also get Git via Git itself for updates:

Git Guides

How to install Git on any OS

Git can be installed on the most common operating systems like Windows, Mac, and Linux. In fact, Git comes installed by default on most Mac and Linux machines!

Checking for Git

To see if you already have Git installed, open up your terminal application.

  • If you’re on a Mac, look for a command prompt application called «Terminal».
  • If you’re on a Windows machine, open the windows command prompt or «Git Bash».

Once you’ve opened your terminal application, type git version . The output will either tell you which version of Git is installed, or it will alert you that git is an unknown command. If it’s an unknown command, read further and find out how to install Git.

Install Git Using GitHub Desktop

Installing GitHub Desktop will also install the latest version of Git if you don’t already have it. With GitHub Desktop, you get a command line version of Git with a robust GUI. Regardless of if you have Git installed or not, GitHub Desktop offers a simple collaboration tool for Git. You can learn more here.

Install Git on Windows

  1. Navigate to the latest Git for Windows installer and download the latest version.
  2. Once the installer has started, follow the instructions as provided in the Git Setup wizard screen until the installation is complete.
  3. Open the windows command prompt (or Git Bash if you selected not to use the standard Git Windows Command Prompt during the Git installation).
  4. Type git version to verify Git was installed.

Note: git-scm is a popular and recommended resource for downloading Git for Windows. The advantage of downloading Git from git-scm is that your download automatically starts with the latest version of Git included with the recommended command prompt, Git Bash . The download source is the same Git for Windows installer as referenced in the steps above.

Install Git on Mac

Most versions of MacOS will already have Git installed, and you can activate it through the terminal with git version . However, if you don’t have Git installed for whatever reason, you can install the latest version of Git using one of several popular methods as listed below:

Install Git From an Installer

  1. Navigate to the latest macOS Git Installer and download the latest version.
  2. Once the installer has started, follow the instructions as provided until the installation is complete.
  3. Open the command prompt «terminal» and type git version to verify Git was installed.

Note: git-scm is a popular and recommended resource for downloading Git on a Mac. The advantage of downloading Git from git-scm is that your download automatically starts with the latest version of Git. The download source is the same macOS Git Installer as referenced in the steps above.

Читайте также:  Автоматическая яркость mac os

Install Git from Homebrew

Homebrew is a popular package manager for macOS. If you already have Homwbrew installed, you can follow the below steps to install Git:

  1. Open up a terminal window and install Git using the following command: brew install git .
  2. Once the command output has completed, you can verify the installation by typing: git version .

Install Git on Linux

Fun fact: Git was originally developed to version the Linux operating system! So, it only makes sense that it is easy to configure to run on Linux.

You can install Git on Linux through the package management tool that comes with your distribution.

  1. Git packages are available using apt .
  2. It’s a good idea to make sure you’re running the latest version. To do so, Navigate to your command prompt shell and run the following command to make sure everything is up-to-date: sudo apt-get update .
  3. To install Git, run the following command: sudo apt-get install git-all .
  4. Once the command output has completed, you can verify the installation by typing: git version .
  1. Git packages are available using dnf .
  2. To install Git, navigate to your command prompt shell and run the following command: sudo dnf install git-all .
  3. Once the command output has completed, you can verify the installation by typing: git version .

Note: You can download the proper Git versions and read more about how to install on specific Linux systems, like installing Git on Ubuntu or Fedora, in git-scm’s documentation.

Other Methods of Installing Git

Looking to install Git via the source code? Learn more here.

Get started with git and GitHub

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

Установка Git в Windows

Система контроля версий Git полезна не только для программистов но и для системных администраторов. Рассмотрим процесс установки программного обеспечения, а также настройки подключения к репозиторию GitHub, на сервере под управлением ОС Windows.

Git — одна из популярных современных систем контроля версий. В основном используется разработчиками программного обеспечения с целью отслеживания изменений в программных продуктах в ходе их разработки. Изначально Git создали для помощи в разработке ядра Linux, однако из-за своих преимуществ, проект ушел в массы.

Приступаем к установке.

Открываем официальный сайт проекта, кликаем по 64-битной версии для Windows.

.

Загрузка начнется автоматически, дожидаемся ее окончания. Запускаем полученный файл.

Программа установки приветствует нас лицензионным соглашением. Кликаем по кнопке “Next”.

На следующем шаге указываем путь установки. Нас устраивает указанный по умолчанию. Кликаем “Next”.

На этапе выбора компонентов, отметим галочкой создание ярлыка Git на рабочем столе и переходим к следующему этапу.

Теперь программа установки предлагает создать ярлык в меню Пуск. Если в этом не видите необходимости, установите соответствующую галку. Кликаем по кнопке “Next”.

На следующем этапе, установщик предложит выбрать редактор для git по умолчанию. Для новичков лучше использовать nano, для тех, кто любит посложнее — Vim. Хотя допускается использование Notepad++ и прочего. Переходим к следующему шагу.

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

  • Use Git from Git Bash only — использование только из командной строки Bash.
  • Use Git from the Windows Command Prompt — использование командной строки Bash, а также минимальный набор команд Git из командной строки Windows.
  • Use Git and optional Unix tools from the Windows Command Prompt — использование Git и утилит Unix из командной строки Windows. При выборе этой опции будут перезаписаны некоторые утилиты ОС Windows, например find и sort.
Читайте также:  Возможно оборудование данного компьютера не поддерживает загрузку с данного диска windows 10

Оставляем первый вариант и двигаемся дальше.

Теперь установщик спрашивает о том, какую библиотеку следует использовать для HTTPS-соединений. Оставляем openssl и переходим к следующему шагу.

Следующий шаг можно назвать самым значимым. Вопрос программы установки в том, какой формат завершения строки использовать. Одной из отличительных особенностей Windows от Unix-подобных систем — символ перехода на новую строку в файлах, а именно, LF и CRLF — управляющие символ для переноса строки в Unix и Windows соответственно.

Мы рекомендуем выбрать параметр предложенный системой — отладка файла в формате Windows, а загрузка файла — в Unix-формате. Кликаем по кнопке “Далее”.

На данном этапе, программа запросит каким терминалом пользоваться далее:

  • MinTTY — терминал Unix;
  • Windows — стандартный терминал (командная строка) Windows.

В нашем случае оставляем “как есть” и двигаемся дальше.

На следующем шаге, установщик попросит отметить необходимые функции:

  • File system caching — кэширование файловой системой.
  • Git Credential Manager — включить менеджер учетных данных.
  • Symbolic links — разрешить использование символьных ссылок.

Выбираем то, что необходимо и переходим к следующему шагу.

На данном шаге, программа установки предлагает использовать экспериментальную опцию. Использовать ее или нет — решать Вам. Кликаем по кнопке “Install”.

Программа приступает к копированию файлов. Дожидаемся окончания процесса.

По окончании процесса установки нажимаем “Finish”.

Подключаемся к репозиторию.

Предполагается, что у вас уже есть своя учетная запись на github/gitlab. Если нет, то, в случае с github, проходим несложный процесс регистрации на сайте. Затем авторизуемся на нем и создаем репозиторий. Для этого кликаем по кнопке “Start a project”.

Указываем имя репозитория и кликаем по кнопке “Create repository”.

Предположим, что у нас есть файл, который необходимо добавить в репозиторий git или gitlab. Открываем папку, где располагается файл, кликаем правой кнопкой мыши по свободному месту и из открывшегося контекстного меню выбираем “Git Bash Here”.

Откроется командная строка. Последовательно выполняем следующие команды:

git config —global user.email «youmail@example.com»

git config —global user.name «Ваше имя»

Таким образом мы указали нашу почту и имя.

Для того, чтобы начать отслеживать изменения в текущей папке, выполняем следующие команды:

Выполняем свой первый коммит и добавляем изменения на сервер:

git commit -m «Init»

Важно. Чтобы внести изменения на сервер, следует использовать для github:

git remote add origin https://github.com/пользователь/название_репозитория.git

git push -u origin master

git remote add gitlab https://server/namespace/project.git

git push -u gitlab master

После запуска команды, откроется окно авторизации. Вводим данные, которые использовали при регистрации.

Настройка аутентификации по SSH-ключам.

Для начала создадим ключ:

В ходе генерации ключа, программа запросит ввод парольной фразы, которая необходима для защиты самого ключа. Можно ответить на вопрос двойным нажатием на Enter.

Закрытый ключ будет находиться по пути C:Users .sshid_rsa. Открытый ключ — C:Users .sshid_rsa.pub

eval $(ssh-agent -s)

Добавляем ключи к ssh-агенту:

Добавляем созданный ключ на сервер Git. На сайте github, в верхнем правом углу, кликаем по иконке учетной записи, выбираем “Setting”.

На обновленной странице, в левом меню, выбираем “SSH and PGP keys”, а в основной части окна, напротив SSH keys, кликаем по кнопке “New SSH key”.

Заполняем поле Title. В поле Key вставляем содержимое файла C:Users .sshid_rsa.pub

Кликаем по кнопке “Add SSH key”.

Если все выполнено правильно, появится примерно такая запись:

Для проверки настроек, выполняем команду:

В ходе выполнения команды, программа запросит: “Уверены ли вы в продолжении соединения”. Это стандартный вопрос безопасности. Отвечаем — yes.

Если все выполнено правильно, программа выведет приветственную речь.

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