Getting git on windows

1.5 Введение — Установка Git

Установка Git

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

В этой книге используется Git версии 2.8.0. Хотя большинство используемых нами команд должны работать даже в старых версиях Git, некоторые из них могут не работать или действовать немного иначе, если вы используете старую версию. Поскольку Git отлично справляется с сохранением обратной совместимости, любая версия после 2.8 должна работать нормально.

Установка в Linux

Если вы хотите установить Git под Linux как бинарный пакет, это можно сделать, используя обычный менеджер пакетов вашего дистрибутива. Если у вас Fedora (или другой похожий дистрибутив, такой как RHEL или CentOS), можно воспользоваться dnf :

Если же у вас дистрибутив, основанный на Debian, например, Ubuntu, попробуйте apt :

Чтобы воспользоваться дополнительными возможностями, посмотрите инструкцию по установке для нескольких различных разновидностей Unix на сайте Git https://git-scm.com/download/linux.

Установка на Mac

Существует несколько способов установки Git на Mac. Самый простой — установить Xcode Command Line Tools. В версии Mavericks (10.9) и выше вы можете добиться этого просто первый раз выполнив ‘git’ в терминале.

Если Git не установлен, вам будет предложено его установить.

Если Вы хотите получить более актуальную версию, то можете воспользоваться бинарным установщиком. Установщик Git для OS X доступен для скачивания с сайта Git https://git-scm.com/download/mac.

Установка в Windows

Для установки Git в Windows также имеется несколько способов. Официальная сборка доступна для скачивания на официальном сайте Git. Просто перейдите на страницу https://git-scm.com/download/win, и загрузка запустится автоматически. Обратите внимание, что это отдельный проект, называемый Git для Windows; для получения дополнительной информации о нём перейдите на https://gitforwindows.org.

Для автоматической установки вы можете использовать пакет Git Chocolatey. Обратите внимание, что пакет Chocolatey поддерживается сообществом.

Установка из исходников

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

Если вы действительно хотите установить Git из исходников, у вас должны быть установлены следующие библиотеки, от которых он зависит: autotools, curl, zlib, openssl, expat, and libiconv. Например, если в вашей системе используется dnf (Fedora) или apt-get (системы на базе Debian), вы можете использовать одну из следующих команд для установки всех зависимостей, используемых для сборки и установки бинарных файлов Git:

Для того, чтобы собрать документацию в различных форматах (doc, html, info), понадобится установить дополнительные зависимости:

Пользователи RHEL и производных от неё (таких как CentOS или Scientific Linux) должны подключить репозиторий EPEL для корректной установки пакета docbook2X

Если вы используете систему на базе Debian (Debian/Ubuntu/Ubuntu-производные), вам так же понадобится установить пакет install-info :

Если вы используете систему на базе RPM (Fedora/RHEL/RHEL-производные), вам так же понадобится установить пакет getopt , который уже установлен в системах на базе Debian:

К тому же из-за различий имён бинарных файлов вам понадобится сделать следующее:

Когда все необходимые зависимости установлены, вы можете пойти дальше и скачать самый свежий архив с исходниками из следующих мест: с сайта Kernel.org https://www.kernel.org/pub/software/scm/git, или зеркала на сайте GitHub https://github.com/git/git/releases. Конечно, немного проще скачать последнюю версию с сайта GitHub, но на странице kernel.org релизы имеют подписи, если вы хотите проверить, что скачиваете.

Затем скомпилируйте и установите:

После этого вы можете получать обновления Git посредством самого Git:

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.

Читайте также:  Обложка для меню пуск windows 10

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:

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:

How to install and use Git on Windows

By default, Git is installed on Linux and macOS computers as a command line option. However, Microsoft Windows does not include a Git command. Below are the steps on how to install and use Git and GitHub on Microsoft Windows.

Installing Git on Windows

  1. Open the Git website.
  2. Click the Download link to download Git. The download should automatically start.
  3. Once downloaded, start the installation from the browser or the download folder.
  4. In the Select Components window, leave all default options checked and check any other additional components you want installed.
  5. Next, in the Choosing the default editor, used by Git unless you’re familiar with Vim we highly recommend using a text editor you’re comfortable using. If Notepad++ is installed, we suggest using it as your editor. If Notepad++ is not installed, you can cancel the install and install Notepad++ and then restart the GitHub install.
  6. Next, in the Adjusting your PATH environment, we recommend keeping the default Use Git from the command line and also from 3rd-party software as shown below. This option allows you to use Git from either Git Bash or the Windows Command Prompt.

  1. Next, we recommend leaving the default selected as Use OpenSSH.
  2. Next, in Choosing HTTPS transport backend, leave the default Use the OpenSSL library selected.
  3. In the Configuring the line ending conversions, select Checkout Windows-style, commit Unix-style line endings unless you need other line endings for your work.
  4. In the Configuring the terminal emulator to use with Git Bash window, select Use MinTTY (the default terminal of MSYS2).
  5. On the Configuring extra options window, leave the default options checked unless you need symbolic links.
  6. Click the Install button
  7. Once completed, you can check the option to Launch Git Bash if you want to open a Bash command line or, if you selected the Windows command line, run Git from the Windows command line.

We highly recommend you use Git from the command line and not use a GUI interface. You’ll only be using the command line to interface with Git to manage the files. Editing can still be done through a text editor or IDE of your choice. If you’re new to the command line, you can find help with navigating the Windows command line and Linux (Bash) through the links below.

Configuring and connecting to a remote repository

In our example, we’re using GitHub as a storage for our remote repository. Below are the steps on how you can connect to a GitHub repository. If you are new to GitHub, see: How to create a GitHub repository.

  1. From the command line, move to the directory you want to contain your Git repository.
  • How to change a directory or open a folder.
  1. Type the following command to configure your Git username, where will be your GitHub username.
  1. After entering the above command, you’ll be returned to the command prompt. Next, enter your e-mail address by typing the following command, where is your e-mail address.
  1. Once the above steps are completed, you’ll be ready to connect to a remote repository. To find the repository address, go to a repository on GitHub and click the Clone or download repository link to get the address. For example, we’ve created a repository called «example» at https://github.com/Computerhope/example.git address. Copy the address to your clipboard.
  2. Once copied go back to the command line and type the following command, where is the address you copied. To paste that address into the command line right-click in the command line window and click paste.
  1. Once the Git repository is created, you’ll have a new directory in your current directory with the name of the Git repository.
  2. Once the Git remote repository is cloned to your local repository, a new folder in the current directory should appear with the name of the Git repository. For example, in our «example» Git we would have a new directory called «example». Use the cd command to change into the new directory.
  3. Once in the new directory, type the following command to list the remote repositories.
  1. If successful, the output is «origin,» which is a special name that refers to the remote repository.
  2. To see the aliases (URL or path), type the following command.
Читайте также:  Realtek high definition audio drivers windows 10 приложение

Running each of the above commands give you an output similar to what is shown in our example below.

Now that you’ve connected to a remote repository on GitHub you’re ready to start working on the files and pushing and pulling files as you update the files.

Working in your local repository and pushing files

After following the above steps and cloning a remote repository, you can work on the files as you normally would. You can create new files or edit existing files from the command line or your favorite text editor. Below, are the steps of creating a new file, pushing that file, editing an existing file, and pushing the update.

Creating a new file and pushing to remote repository

  1. Create a new file in the Git directory by typing the following command from either the Bash or Windows command line. The following command opens and creates a file called example.txt in Notepad. In Git Bash, you could also use the touch command to create a blank new file and then type «start » to open the file in your favorite text editor.
  1. In the text editor, enter some text into the file and save and exit the file.
  2. Back at the command line type the following command to get the current status of your branch and untracked files.
  1. Git displays a window similar to the example shown below, showing that the file we created is new and untracked by Git.

  1. We’ll now want to add this file to Git to be tracked by typing the following command. If your file is not named «example.txt,» you’d want to change the text to the name of your file.
  1. After entering the above command, the file is added as a new file also known as staging. Typing git status again shows you in green that the file is a new file that is ready to be committed.
  2. Next, type the following command to commit the changes made in the local workspace to the local repository. In the example below, our notes «First example» should be notes that would make sense everyone working on your project.

You can also type git commit with no additional tags or options. However, when doing this it opens a vim like editor that can be difficult for those not familiar with the vim to use. If you type this command press «i» to enter insert mode and type the notes for the commit on the first line, press Esc, and then type «:wq» to save, exit, and commit. We suggest using the above command because it’s easier for more people to use.

  1. Finally, now that changes are moved from your workspace into your local repository it’s ready to be pushed to the remote repository. Type the following command to push all changes to the remote repository.

If you want to follow the progress, you can type git status again to see the current status. You can also type git log to see a log of changes.

You’ll be asked for your GitHub username and password if your computer has not logged in to Git from the command line.

Once the file is pushed, it appears in your GitHub remote repository and is available to everyone else who’re working with the same repository.

Modifying a file and pushing to remote repository

  1. Edit and modify one or more files in your Git.
  2. Type git status to see the status of all the files not yet committed from the workspace to the local repository.
  3. Type the following command to add all files. The single period indicates that you want all files to be added to the local repository. Some people may also use git add -A to add all.
Читайте также:  Код для покупки minecraft windows 10 edition

You can also use wildcards instead of a period. For example, if you wanted to add all text files you could type *.txt instead of a single period to only add text files.

  1. Once the files are added, type the following command to commit. Change the notes to apply to your commit.
  1. Finally, type git push to push the commit to the remote repository.

If you’re working with a lot of other people, we’d recommend you pull (explained below) before committing. If your local repository is not the same as the remote repository (excluding your new changes), the commit fails. For example, if someone has added new files to the remote repository while you’ve been working and you try commit, it fails until you pull.

Pulling or fetching updates from the remote repository

If it’s been awhile since you’ve committed any work, perform the git pull command to get the latest updates from the remote repository and merge them into your local repository. By pulling updates from a repository before committing, it verifies your local repository and the remote repository are the same and prevents merge conflicts.

To get all changes without merging, run the git fetch command to grab all of the latest updates from the remote repository without merging changes.

How to deal with a Git merge conflict

When multiple people are working with the same files, you’re going to encounter merge conflicts. When a conflict occurs, Git modifies your local files and it is up to you to manually fix the files with the conflicts.

Use the git status command to see the status and merge conflict information.

Open the file with the conflict to start correcting the errors. In the example file below, we had a text file with one line of text and in the local repository we added the text «update1» to the file. However, during the same time, the remote repository file was modified and added «update2″ to the file on the same line. Git marks conflicts with » >>>>>> » to mark the end.

To resolve this merge conflict, we would need to decide what text we wanted to keep, update, or remove. In this example, we want to keep «update1» and «update2» in the order they’re listed so we would only need to remove the Git markings to make the file resemble the following example.

If you’re working with a big file, it’s a good idea to search the file for «HEAD» because there may be more than one conflict.

Once the changes are made in the file, we could save the file and then perform the following git commands to update the fixes.

The example given in this merge conflict is a very basic example. When dealing with a file with more than a few lines of text or big sections of code, merge conflict can get a lot more confusing. To make it easier to deal with merge conflicts, you can use the command git mergetool to use a merge tool, such as WinMerge or another popular merge tool.

Creating a Git branch

Creating a branch allows you to create a duplicate of the master (trunk) and make several updates without affecting the master. For example, when developing a program if a big fix was need that could take weeks or months, a branch could be created for that fix. Once you’ve fixed the bug, you could merge your branch back into the master.

To create a branch in your local repository, follow the steps below.

  1. In the Git master directory, type the following command, where » » is the name of the new branch name. For example, we could call the branch «examplebranch».
  1. Next, type the following command to switch to the branch.
  1. After entering the above command, the prompt (in Git Bash) changes from «master» to the branch name to indicate you’re working in a branch.
  2. From this point, you can continue to use Git and modify the files how you have in the past.
  3. To see all available branches, you can use the git branch command. For example, typing git branch displays your local repository branches. Typing git branch -a displays all local and remote repositories.
  4. If you need to push the branch to the remote repository, you can run the following command.
  1. Finally, if you need to switch back to the master branch, you can type the following command.

How to merge a branch back into the master

After completing your work, you’ll want to merge it back into the master or another branch by following the steps below.

  1. Move into the branch you want to merge into. For example, if you wanted to merge back into the master, type the following command.
  1. Once in the master, type the following command to merge the branch.
  1. Once the merge is performed, add the files.
  2. Next, commit the changes.
  3. Once merged and committed, push the merge by typing the following command. If you get conflicts during the merge, see our how to deal with merge conflicts section.

How to delete a local and remote branch

If, after merging a branch you no longer want to keep the local or remote branch, you can perform the following commands.

To delete the local branch, type the following command.

To delete the remote branch, type the following command.

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