Using git on linux

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.

Читайте также:  Linux mint virtualbox разрешение экрана

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:

Источник

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.

Читайте также:  Не работает windows mobile center win 10

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.

Источник

Как пользоваться GitHub на компьютере с Linux

GitHub — один из используемых сервисов размещения проектов для совместной разработки. Он поддерживает контроль версий, возможность отслеживания изменений кода, сравнение строк, а также он бесплатен.

В данной статье приведены примеры использования сервиса на компьютере под управлением операционных систем семейства Linux. Мы рассмотрим, как создать проект на локальном компьютере и залить его на сервис с помощью командной строки. Рассмотренные варианты использования git также можно применять на desktop системах, запустив окно терминала.

Установка git

Управление выполняется с помощью приложения git. Если его нет в системе, установку можно выполнить из репозитория.

Если используем CentOS / Red Hat:

yum install git-core

Если используем Ubuntu / Debian:

apt-get install git

Если мы хотим воспользоваться сервисом с компьютера Windows или Mac OS, необходимо скачать и установить desktop версию с официального сайта.

Синтаксис

Команды имеют следующий синтаксис:

* полный перечень опций, команд и аргументов можно получить командой man git.

Создание проекта на локальном компьютере

Прежде чем отправить проект на GitHub, создаем его на нашем компьютере. Для этого переходим в каталог с файлами проекта:

Инициализируем проект для git:

Мы получим ответ похожий на:

Initialized empty Git repository in /projects/.git/

Это означает, что репозиторий git создан.

Теперь добавим файлы в репозиторий:

* данной командой мы добавили папку и ее содержимое в репозиторий git.

Отправка данных на GitHub

Теперь можно отправить данные на сервис. Для этого у нас должна быть зарегистрированная учетная запись и создан репозиторий на GitHub.

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

Переходим на портал github.com и входим в систему или проходим несложную регистрацию:

Проходим процесс подтверждения, что мы не робот. Затем завершаем несколько шагов регистрации, нажимая Submit. В итоге мы получим письмо на адрес электронной почты, которую указали при регистрации. Необходимо будем подтвердить email, перейдя в письме по кнопке Verify email address.

Создаем репозиторий. Для этого кликаем по иконке профиля и переходим в раздел Your repositories:

Читайте также:  С windows syswow64 werfault exe что это

И кликаем по кнопке New. В следующем окне даем название репозиторию и нажимаем Create repository:

Мы увидим страницу с путем к репозиторию:

Заливаем проект в репозиторий на GitHub

Добавляем комментарий к нашему проекту:

git commit -m «Очередное изменение проекта» -a

* где Очередное изменение проекта — произвольный комментарий; параметр -a указывает, что комментарий нужно применить ко всем измененным файлам.

Теперь подключаемся к созданному репозиторию:

git remote add origin https://github.com/dmosktest/project1.git

* где dmosktest — логин, который был указан при регистрации на github, а project1 — название, которое мы задали, когда создавали репозиторий.
* удалить удаленный репозиторий можно командой git remote rm origin.

Закидываем проект на GitHub:

git push origin master

* где master — ветка проекта (веток может быть несколько).

В нашем проекте на GitHub должны появиться файлы проекта:

Получение файлов с GitHub

Для загрузки на компьютер файлов, создаем каталог с проектом и переходим в него:

Проводим начальную настройку локального репозитория:

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

git remote add origin https://github.com/dmosktest/project1.git

Скачиваем проект командой:

git pull https://github.com/dmosktest/project1.git master

Клонирование проекта

Например, использую наш репозиторий:

git clone https://github.com/dmosktest/project1.git

* данная команда создаст в текущей папке каталог project1 и инициализирует его как локальный репозиторий git. Также загрузит файлы проекта.

Возможные ошибки

1. При попытке отправить данные на GitHub, получаем ошибку:

error: src refspec master does not match any.
error: failed to push some refs to ‘https://github.com/dmosktest/project1.git’

* где dmosktest/project1.git — путь к нашему репозиторию.

Причина: проект ни разу не был зафиксирован (закоммичен).

Решение: добавляем комментарий к нашему проекту:

Источник

Начало работы с Git на Linux

Что такое Git

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

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

Если вы используете Ubuntu VPS, то установите Git в вашей системе, используя следующие команды:

Если вы используете CentOS VPS, вы можете использовать следующую команду для установки Git:

Чтобы проверить, какая версия Git установлен в вашей системе, используйте:

Настройка Git на Linux

Теперь, когда у вас есть Git, установленной на вашем Linux VPS, вы можете приступить к конфигурации Git. В принципе, вам нужно будет настроить ваше имя и адрес электронной почты. Таким образом, фиксация сообщений будет содержать правильную информацию. Чтобы обновить ваше имя и адрес электронной почты, вы можете использовать следующие команды:

Конечно, вам нужно заменить “Ваше имя” и user@domain.ru на вашу собственную информацию.

Для проверки информации о конфигурации можно использовать:

Создать репозиторий Git

Как создать каталог для вашего первого проекта.

Команда выше создаст новый каталог с именем git_repo внутри вашей домашней директории. Не стесняйтесь использовать другое имя.

Чтобы инициализировать пустой репозиторий Git в каталоге, который вы только что создали, используйте следующую команду:

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

Поскольку хранилище не содержит каких-либо файлов, вы увидите что-то вроде этого:

После создания файла, вам необходимо добавить содержимое файла в индекс. Вы можете сделать это с помощью следующей команды:

Тем не менее, эта команда не влияет на хранилище. Для записи изменений в хранилище, вы должны выполнить команду ниже:

Для помощи по командам Git вы можете использовать следующую команду:

Это список наиболее часто используемых команд Git:

Для получения дополнительной информации и примеры использования вы можете прочитать официальную документацию Git , которая доступна на https://git-scm.com/doc

PS . Если вам понравился этот пост, пожалуйста, поделитесь им с друзьями в социальных сетях с помощью кнопок соц сетей или просто оставьте комментарий ниже. Заранее благодарю.

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

Источник

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