Установка Git в Ubuntu
Система контроля версий — это незаменимая вещь при совместной разработке программного обеспечения. Такие программы позволяют отслеживать изменения в вашем исходном коде и при необходимости восстанавливать прошлое состояние.
Одной из самых популярных систем управления версиями заслуженно считается Git. Многие проекты хранят свои файлы в репозиториях Git, а сайты GitHub и Bitbucket сделали обмен исходным кодом очень простым. В этой небольшой статье будет рассмотрена установка Git в Ubuntu. Мы рассмотрим два способа установки, а также начальную конфигурацию.
Установка Git с помощью пакетного менеджера
Самый простой способ установить Git в Ubuntu 20.04 или других версиях, это использовать пакетный менеджер apt и официальные репозитории Ubuntu. Это самый быстрый и простой метод, но вы получите не самую свежую версию.
Для установки Git с помощью пакетного менеджера. сначала обновим списки пакетов из репозиториев:
sudo apt update
Затем осталось загрузить и установить программу:
sudo apt install git
После этого программа будет установлена и вы можете переходить к ее настройке. Для просмотра версии выполните:
Установка Git из исходных кодов
Более гибкий, но в то же время самый сложный способ установки Git в Ubuntu — это сборка из исходных кодов. Процесс установки займет больше времени, но вы получите больше контроля над параметрами программы, а также сможете установить самую последнюю версию.
Перед тем, как приступить нам нужно будет скачать пакеты, от которых зависит Git. Все есть в официальном репозитории, поэтому вы можете все сделать с помощью пакетного менеджера:
sudo apt update sudo apt install build-essential libssl-dev libcurl4-gnutls-dev libexpat1-dev gettext unzip
После того как все будет установлено вы можете скачать архив с самыми последними версиями исходного кода. Это можно сделать на странице релизов. Здесь есть как rc релизы, так и стабильные версии.
Когда выберите версию, нажмите кнопку Download zip. Или же скопируйте ссылку чтобы скачать с помощью терминала. Например, на данный момент самая последняя версия — 2.10.1. Вы можете использовать адрес файла вместе с wget, чтобы скачать исходники:
wget https://github.com/git/git/archive/v2.28.0.zip -o git.zip
Распакуйте только что загруженный файл с помощью unzip и переместитесь в каталог с файлами архива:
unzip git.zip cd git-*
Дальше переходим к сборке программы и ее установке:
make prefix=/usr/local all sudo make prefix=/usr/local install
После того как вы установили Git таким способом, вы можете просто ещё раз клонировать репозиторий и выполнить две последние команды для обновления. Для клонирования нужно знать URL репозитория. Например, для текущей ветки master, этот url будет выглядеть вот так:
git clone https://github.com/git/git
Затем просто соберите новую версию git с помощью тех же команд:
cd git make prefix=/usr/local all sudo make prefix=/usr/local install
После выполнения старая версия будет заменена новой. Причем, старые исходники сохранятся, так что в случае ошибок вы сможете восстановить старую версию. А теперь давайте рассмотрим как выполнить минимальную настройку Git, чтобы с программой можно было работать.
Настройка Git в Ubuntu
После того как установка Git Ubuntu будет завершена одним из выше перечисленных способов, вам нужно еще кое-что сделать перед тем, как вы сможете полноценно работать. Вам нужно идентифицировать себя указав имя пользователя и адрес электронной почты.
Самый простой способ это сделать — с помощью команды git config. Git использует имя пользователя и Email при каждом коммите, так что задавать их обязательно. Для этого выполните команды:
git config —global user.name «Your Name» git config —global user.email «youremail@domain.com»
Вы можете посмотреть установленные параметры с помощью команды:
git config —list
Вся информация хранится в вашем конфигурационном файле Git, поэтому вы можете отредактировать его вручную если это необходимо с помощью текстового редактора:
[user] name = Имя email = youremail@domain.com
Здесь можно установить много других параметров, но именно эти два самые важные, потому что если вы попытаетесь что-то сделать когда они не установлены, то увидите предупреждение:
Выводы
Теперь вы знаете как выполняется установка Git Ubuntu 20.04. Мы рассмотрели два способа — простой и быстрый, а также сложный, но более гибкий. Если у вас остались вопросы спрашивайте в комментариях!
Как установить git на ubuntu
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
- Navigate to the latest Git for Windows installer and download the latest version.
- Once the installer has started, follow the instructions as provided in the Git Setup wizard screen until the installation is complete.
- Open the windows command prompt (or Git Bash if you selected not to use the standard Git Windows Command Prompt during the Git installation).
- 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
- Navigate to the latest macOS Git Installer and download the latest version.
- Once the installer has started, follow the instructions as provided until the installation is complete.
- 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.
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:
- Open up a terminal window and install Git using the following command: brew install git .
- 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.
- Git packages are available using apt .
- 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 .
- To install Git, run the following command: sudo apt-get install git-all .
- Once the command output has completed, you can verify the installation by typing: git version .
- Git packages are available using dnf .
- To install Git, navigate to your command prompt shell and run the following command: sudo dnf install git-all .
- 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.
Subscribe to our newsletter
Get product updates, company news, and more.
Product
- Features
- Security
- Team
- Enterprise
- Customer stories
- The ReadME Project
- Pricing
- Resources
- Roadmap
Platform
- Developer API
- Partners
- Electron
- GitHub Desktop
Support
- Docs
- Community Forum
- Professional Services
- Skills
- Status
- Contact GitHub
Company
- About
- Blog
- Careers
- Press
- Inclusion
- Social Impact
- Shop
- GitHub on Twitter
- GitHub on Facebook
- GitHub on LinkedIn
- GitHub on YouTube
- GitHub on Twitch
- GitHub on TikTok
- GitHub’s organization on GitHub
- © 2023 GitHub, Inc.
- Terms
- Privacy (Updated 08/2022)
- Sitemap
- What is Git?
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
How to Install Git on Ubuntu Using APT and GitHub (Ubuntu 18.04, 20.04, and 22.04)
Modern software development requires a lot of work to be successful. One of the most important steps is choosing a distributed version control system.
Such systems help you keep track of every code change and revert previous stages if needed. One of the most popular version control systems is Git.
In this tutorial, we’ll show two simple ways how to install Git on Ubuntu and how to configure it.
How to Install Git on Ubuntu
Git installation on an Ubuntu system requires three essential objects:
- Ubuntu version – this tutorial covers Ubuntu’s three most recent versions – 18.04, 20.04, and 22.04. Ensure that one of these versions is running on your computer or a virtual private server (VPS).
- Sudo privileges – an account with sudo privileges is required to install Git. It can be a root account or a separate user account with administrator privileges.
- Access to the terminal – Git installation will include commands that must be entered into the terminal window.
Step 1 – Install Git on Ubuntu
There are two ways to install Git on Ubuntu. We’ll break them down one by one, but you can choose which one works best for you. It’s worth noting that both require access to the terminal.
Installing Git With APT
Ubuntu already has Git in the default repository. It can be easily installed with the help of the APT package management tool:
- Update the repository by running the following command:
- Install Git with this command:
- When asked for permission to install Git, type Y, and press Enter.
Keep in mind that the Git version in the APT package manager might differ from the recent version found on the GitHub source website. You can check the available versions using this command:
Here’s an example of what the output would look like:
There are two available versions – 2.17.1 and 2.17.0. The candidate version shows which version will be installed.
Alternatively, use this command after installing Git to check the version:
Installing Git from GitHub
We recommend proceeding with the GitHub installation method if you want to install a different version of Git:
- Update the repository by running the following command:
- Install all the necessary GitHub packages:
- Visit the Git for Linux download page, right-click on the latest stable version, and copy the link. In our case, it’s the 2.36.1 version.
- Go back to the terminal and use the following command with the copied link:
- To extract the file, run this command:
- Once the process is finished, head to the extracted directory:
- Install Git globally by running this command:
- To verify the installation, use the following command prompt:
If a Git version number appears, that means the installation was successful.
Pro Tip
The previous method will install Git globally. If a local installation is needed, refer to the INSTALL file located in the archive for instructions.
Step 2 – Configure the Git Account
Once Git is installed, you will need to configure it with the Git config command.
- Specify your GitHub username on the terminal:
Replace the “user_name” argument with an actual username, quotation marks included.
- Specify the email address:
Make sure to replace “email@myawesomedomain.tld” with an actual email address, quotation marks included.
- Verify the changes:
Pro Tip
Installing and configuring the Git version control system is just one step to becoming a skillful developer. If you want to learn more, check out our comprehensive Git tutorial.
Conclusion
Git is one of the world’s most popular distributed version control systems. This free tool offers many valuable features and allows developers to perform any code changes with the ability to revert the changes if needed.
This tutorial covered how to install Git on Ubuntu 18.04, 20.04, and 22.04 via APT or GitHub. You also learned how to configure Git using your username and email address.
If you have any further insights or questions, leave them in the comments section below.
How To Install Git on Ubuntu FAQ
How to Check if Git Is Already Installed?
The easiest way to check if Git is installed is to run the git –version command, which will display the current version of Git.
Another option is to run any Git command like git build. If an error message such as “git: command not found” appears, it means that Git is not installed on the system.
What Is the Default Git Install Location on Ubuntu?
Users can install Git either globally or locally. Git will be installed under the /usr/bin/git directory if you’re going with the global method. This can always be double-checked using the whereis git command, showing the exact Git installation directory.
However, if users use the local installation method, Git will only work on that particular directory. For example, if a user installs Git on the /home/username directory, they will need to navigate to this directory to use Git.
Elvinas is a senior server administrator at Hostinger. He monitors the infrastructure’s well-being and keeps the uptime at a maximum. Besides server management, web development has always been one of his biggest passions.
Introduction
Git is an open source, distributed version control system designed to handle everything from small to very large projects with speed and efficiency.
Every Git clone is a full-fledged repository with complete history and full revision tracking capabilities, not dependent on network access or a central server. Branching and merging are fast and easy to do.
Installation
Before starting, make sure that:
* You already have a Ubuntu 9.04 or Ubuntu 10.04 (or a newer version) installed on you computer/server.
* You already have a public ssh key on your local machine you can use that to initialize the repository. Don’t have one? Look here.
* You have customised an editor by setting the environment variable EDITOR to your favourite editor. (see below)
The following instructions will guide you on how to set up and run a fully managed hosting for projects using git on your server.
WARNING This guide is written for Gitosis, which has been out of active devolpment since 2008, and no is longer available in later versions of Ubuntu such as Version 12.04. Gitosis seems to have been replaced by Gitolite.
Choose an Editor
You may have a favourite text editor that you like to use, so you’ll need to specify it by exporting the EDITOR environment variable with the name of the editor binary.
This example sets vim as the editor for use throughout this guide, i.e:
If you want to use another editor like nano, pico or gedit then you replace vim with either nano, pico or gedit. Remember that gedit (and other Desktop editors like it) requires a valid Xserver display to be available.
Used software
This tutorial was done using Ubuntu 9.04 (Jaunty Jackalope), Ubuntu 10.04 (Lucid Lynx).
We’ll be using the latest git package available in the archive.
For git project management will be using Gitosis.
For repository web browsing we will be using ViewGit. The latest version we will clone directly from a git repository: git clone git://repo.or.cz/viewgit.git
Setting up Git and Project Management
Use your favorite package installer to install git-core and gitosis packages:
Installing the gitosis package will create the user gitosis and the home directory for it at /srv/gitosis, which contains the repositories and configuration information.
Now that you should have both packages installed and a gitosis user, we can set up gitosis.
Initialize gitosis using your key:
where initialKeyFileName name is the name of a copy of the public key from your local machine which is on the server (i.e. the file ending in .pub)
If you saw some output like this: Initialized empty Git repository in ./ Your gitosis is installed.
Once done, you can now checkout the gitosis-admin branch on your local machine:
. but replace yourserver.com with the actual name of your server. Note that gitosis is an account already on your system that was created when you installed the gitosis package.
If the cloning doesn’t work, maybe you have PermitRootLogin no in the SSH server, and you need to allow the gitosis user in sshd_config:
WARNING This blocks all users other than gitosis from ssh access. Refer to the sshd_config manpage : . If AllowUsers is specified, login is allowed only for user names that match one of the patterns .
Use your favorite editor to modify the contents of the gitosis configuration file on your local machine (changes will be pushed back to server in next step):
Adding a new project to the repository
Here is an example of the gitosis configuration file you cloned before. Here it contains the default gitosis entry, and a new project entry:
Warning: Be careful with this step, if you mess with the gitosis-admin group you could lock yourself out of the repository.
keyfilename is the name of the public key without .pub extension. Note: This is not necessarily the same filename as initialKeyFileName, but the one in the /keydir folder of gitosis-admin.
After you’re done editing, save the file, and commit it back to the server.
Any future projects will be added the same way.
Committing to the first project
To commit the project you just created, initiate a new git project, add files to it, commit it, then push it to your repository with the name you set up in gitosis config file.
The project should be committed!
If not, please check your /srv/gitosis/.ssh/authorized_keys file, if that one contains your correct public key!
Adding users
First, gather their public SSH keys, which I’ll call «kakashi.pub» and «naruto.pub», and drop them into keydir/ of your local gitosis-admin repository. Second, edit gitosis.conf and add them to the «members» list.
Note that the key filename must have a «.pub» extension.
Commit and push:
That’s it. Kakashi and Naruto can now clone the testproject repository like so:
Kakashi and Naruto will also have commit rights.
The web browsing interface
Server will need a web server so I recommend you to install Apache with support for php. Once ViewGit can be linked to GeSHI, I also recommend you installing the php-geshi package:
For more extended Apache installation we recommend you reading a dedicated page like this ApacheMySQLPHP.
Once done, /var/www/ directory will be created. Go there and clone the latest git version of !ViewGIT:
After finishing this operation, use your favorite editor to edit the config file for ViewGit:
What follows is an example of the ViewGit localconfig.php with !GeSHI and the testproject.git we created.
Although there are two things to note :
* $conf[‘projects’] will be an array that you explicitly define repositories that viewgit will display. * $conf[‘projects_glob’] is an array of file-system path patterns that gitweb will use to search for *.git directories. This provides easier inclusion of all your repositories (although it may ignore any gitweb directives in your gitosis.conf)
Both $conf[‘projects’] and $conf[‘projects_glob’] will be used to decide what projects to display. So in the following example if you actually created the testproject example in the previous steps, it will show up twice.
Now you should be able to browse your Git repository by going to http://localhost/viewgit/ if you got problems on accessing repositories, add your web server user to the same group gitosis user is:
Making available public cloning of the projects
To make available public access for cloning of the projects, you have to set up git-daemon. git-daemon is a service which runs on port 9418 and handles public requests for project cloning. git-daemon comes together with git-core so no additional installation is required.
To make this service easier to administrate, here is an init script to start and stop the daemon.
It is, however, easier to make git a subservice of xinetd, by editing /etc/xinetd.d/git and changing disable=no>> to <<
Create the git-daemon init script
paste the following
To make it usable, and make possible it's automatic startup on server boot change its permissions and update-rc.d
The daemon can be controlled in the following manner :
Ubuntu 9.10 and later :
Git (последним исправлял пользователь antoine-dymond 2012-11-01 14:56:02)
The material on this wiki is available under a free license, see Copyright / License for details
You can contribute to this wiki, see Wiki Guide for details