- Что такое репозитории в Linux – подробное описание для начинающих
- Что такое пакет в Linux?
- Как устанавливаются программы в Linux?
- Что такое репозиторий в Linux?
- Какие бывают репозитории в Linux?
- Как работать с репозиториями в Linux?
- Ubuntu Documentation
- The Basics
- Explanation of the Repository Format
- Other Versions
- Adding Repositories
- Adding the Universe and Multiverse Repositories
- Adding Partner Repositories
- Adding Other Repositories
- Adding Launchpad PPA Repositories
- Enabling Repositories with a (non-interactive) Script
- Suggestions & Recommendations
- How to Update the List of Linux Repositories
- What are Linux repositories?
- Different types of repositories in Ubuntu
- How to add new repositories to the software list
- Example to add Google Chrome repository from Terminal
- How to update the list of Linux repositories
Что такое репозитории в Linux – подробное описание для начинающих
Всем привет! Сегодня я расскажу о том, что такое репозитории в Linux, для чего они нужны, какие виды репозиториев бывают, а также покажу, как работать с этими репозиториями, и какие инструменты для этого используются.
Чтобы понять, что такое репозитории в Linux и для чего они нужны, нужно немного разобраться в архитектуре самой операционной системы Linux, в частности, как устанавливаются программы (пакеты).
Углубляться в дебри мы не будем, но саму концепцию рассмотрим.
На заметку! Новичкам рекомендую почитать мою книгу «Linux для обычных пользователей» – в ней я подробно рассказываю про основы операционной системы Linux и как пользоваться этой системой без командной строки
Давайте обо всем по порядку.
Что такое пакет в Linux?
В Windows программы обычно распространяются в виде exe файлов или в каком-нибудь специально упакованном формате. В Linux программы распространяются в виде пакетов.
Пакет в Linux – это своего рода дистрибутив программы, набор необходимых файлов, которые необходимы для работы этой программы, упакованный в специальный формат.
Существуют два популярных формата пакетов:
- DEB – формат файлов пакетов, использующихся в дистрибутиве Debian и во всех основанных на нем дистрибутивах, таких как: Ubuntu, Linux Mint и другие;
- RPM – менеджер пакетов, использующийся в дистрибутиве Red Hat, а также во многих других популярных дистрибутивах, таких как: openSUSE, CentOS, Mageia и других.
Как устанавливаются программы в Linux?
Все программы, а точнее пакеты, устанавливаются в систему с использованием централизованного метода, т.е. из единой точки, такой точкой может быть либо инструмент с графическим интерфейсом, часто его называют «Менеджер приложений», либо традиционный для Linux способ, утилиты командной строки (терминала).
Процесс установки программ с использованием такого подхода предполагает простой выбор программы, которую необходимо установить, и ее установка одним кликом, все остальное сделает менеджер приложений.
Ярким примером использования такой концепции представлен на всех смартфонах (ведь Android это Linux!), где для установки приложения Вы просто открываете менеджер программ (например, Play Маркет), находите нужную программу, и нажимаете установить и все!
Таким образом, в большинстве случаев для установки программ в Linux не требуется предварительно искать и скачивать с интернета дистрибутив программы, как например в Windows, достаточно запустить менеджер приложений, найти интересующее приложение и запустить установку.
Что такое репозиторий в Linux?
Если нам не нужно самостоятельно скачивать дистрибутивы программ с интернета, то как тогда они попадают на компьютер?
И чтобы сразу внести ясность, на компьютерах пакеты программ не хранятся, менеджер скачивает их автоматически во время установки.
А откуда тогда менеджер скачивает все эти пакеты? А скачивает он их со специальных серверов в интернете (поэтому для установки программ в Linux требуется интернет), которые называются – репозиториями.
Репозитории – это сервера в интернете, на которых хранятся файлы пакетов приложений Linux и другая сопутствующая информация.
Практически у каждого дистрибутива Linux есть свой репозиторий, который содержит только совместимые и поддерживаемые конкретным дистрибутивом пакеты, соответственно, при установке приложений из официальных репозиториев Вы всегда устанавливаете только проверенные и стабильные версии программ.
Официальный репозиторий дистрибутива по умолчанию подключен, и когда Вы пытаетесь найти и установить программу, «Менеджер приложений» считывает информацию о доступных пакетах в репозитории и выдает ее Вам.
Таким образом, когда открываете менеджер приложений, он обращается к репозитоирию, узнает, какие пакеты есть, и выдает этот список Вам, а Вы, соответственно, выбираете и нажимаете кнопку установить, а все остальное делает менеджер.
Существуют, конечно, и нюансы при работе с таким подходом установки программ, например, что программа, которая Вас интересует, должна находиться в репозиториях конкретного дистрибутива Linux, который установлен на компьютере, в противном случае ее придётся искать в интернете, иными словами, делать ровно то же самое, что и в Windows. Однако популярные дистрибутивы Linux содержат в своих стандартных репозиториях тысячи программ на любой вкус, которые могут удовлетворить потребности даже продвинутого пользователя Linux, не говоря уж о начинающем.
Какие бывают репозитории в Linux?
Репозитории бывают как основные, т.е. официально поддерживаемые, так и дополнительные, которые можно подключить в случае возникновения необходимости (например, программы, которую Вы искали, нет в официальном репозитории).
Обычно у дистрибутива несколько официальных репозиториев, в каждом из которых хранятся пакеты, в зависимости от определенных свойств, так, например, в Ubuntu есть следующие типы официальных репозиториев:
- Main – здесь расположено основное, полностью бесплатное программное обеспечение;
- Restricted – проприетарное программное обеспечение, официально поддерживаемое дистрибутивом;
- Universe – бесплатное программное обеспечение, официально поддерживаемое сообществом дистрибутива;
- Multiverse – проприетарное программное обеспечение, не поддерживаемое дистрибутивом.
Если программы, которую Вы искали, нет в официальном репозитории, то Вы можете подключить дополнительный, в котором есть нужная Вам программа.
Например, дополнительные репозитории в Ubuntu и основанных на нем дистрибутивах называются PPA-репозитории.
PPA (Personal Package Archive) – это персональный репозиторий разработчика конкретной программы, где он хранит пакеты своих программ, которые еще не включены в основной репозиторий дистрибутива.
Как работать с репозиториями в Linux?
Если репозиторий – это некий сервер в интернете, на котором хранятся программы, то, чтобы к нему обратиться за необходимой нам программой, мы должны знать адрес этого сервера. Один из самых удобных способов обращения к ресурсам в интернете – это использовать веб протоколы взаимодействия, таким образом, по факту адрес репозитория выглядит, как обычный URL-адрес сайта.
Для того чтобы система знала и помнила, куда обращаться за пакетами (программами), она хранит все адреса репозиториев в специальном файле sources.list, который расположен в каталоге в /etc/apt. И вся работа с репозиториями в Linux заключается в добавлении и удалении адресов репозиториев.
Таким образом, если обобщить весь этот процесс, то, когда мы пытаемся установить программу, система предварительно считывает список доступных пакетов во всех подключенных репозиториях. И если такая программа есть, система устанавливает ее, если нужного пакета нет, то, соответственно, не устанавливает. И нам в этом случае, если мы хотим установить программу, необходимо подключить нужный репозиторий, т.е. добавить адрес этого репозитория.
Работать с репозиториями в Linux можно несколькими способами, в частности новички могут использовать удобный графический интерфейс, а более продвинутые пользователи Linux обычно пользуются специальными командами в терминале Linux.
В любом случае весь процесс работы с репозиториями сводится к редактированию файла sources.list (а также созданию дополнительных подобных файлов), который, кстати, Вы можете отредактировать и обычными утилитами для работы с текстовыми файлами.
Обычно компонент с графическим интерфейсом для работы с репозиториями называется «Источники приложений», он доступен из основного меню операционной системы.
Например, в Linux Mint он выглядит следующим образом
Для управления репозиториями в терминале используется команда add-apt-repository, так, например, для добавления PPA-репозитория команда будет выглядеть следующим образом.
где, ppa:atareao/telegram – это PPA-репозиторий для установки программы Telegram.
Более подробно про то, как добавлять и удалять репозитории в Linux, я расскажу в следующих материалах. Поэтому следите за выходом новых статей в моих группах в социальных сетях: ВКонтакте, Facebook, Одноклассники, Twitter и Tumblr. Подписывайтесь, и Вы не пропустите выход нового материала!
На сегодня это все, надеюсь, материал был Вам полезен и интересен, удачи Вам, пока!
Источник
Ubuntu Documentation
This page describes how to manage software repositories from the command line. (GUI tools are also available: Managing Repositories in Ubuntu or Kubuntu).
If you are using a minimal install or server install you will need to be familiar with a terminal based text editor like nano. If you are using a GUI install you can use Nano or GEdit.
The Basics
Ubuntu uses apt for package management. Apt stores a list of repositories or software channels in the file
and in any file with the suffix .list under the directory
See man sources.list for more about this storage mechanism.
By editing these files from the command line, we can add, remove, or temporarily disable software repositories.
Note: It’s always a good idea to backup a configuration file like sources.list before you edit it. To do so, issue the following command:
Typically, the beginning of the file /etc/apt/sources.list looks like this:
Explanation of the Repository Format
- All the lines beginning with one or two hashes (#) are comments, for information only.
The lines without hashes are apt repository lines. Here’s what they say:
deb: These repositories contain binaries or precompiled packages. These repositories are required for most users.
deb-src: These repositories contain the source code of the packages. Useful for developers.
http://archive.ubuntu.com/ubuntu: The URI (Uniform Resource Identifier), in this case a location on the internet. See the official mirror list or the self-maintained mirror list to find other mirrors.
saucy is the release name or version of your distribution.
main & restricted are the section names or components. There can be several section names, separated by spaces.
Other Versions
For other Ubuntu releases you would replace the ‘saucy’ with the current version you have installed (‘precise’, ‘quantal’, ‘raring’, ‘saucy’, ‘trusty’, . ) Type lsb_release -sc to find out your release.
Adding Repositories
Adding the Universe and Multiverse Repositories
Additional software repositories such as Universe and Multiverse can be enabled by uncommenting the corresponding apt lines (i.e. delete the ‘#’ at the beginning of the line). For Universe, uncomment those lines:
There are four similar lines for ‘multiverse’.
OR you may use the add-apt-repository command. If your release is ‘saucy’:
Depending on your location, you should replace ‘us.’ by another country code, referring to a mirror server in your region. Check sources.list to see what is used!
Type lsb_release -sc to find out your release. You may repeat the commands with «deb-src» instead of «deb» in order to install the source files.
Don’t forget to retrieve the updated package lists:
Adding Partner Repositories
You can add the partner repositories by uncommenting the following lines in your /etc/apt/sources.list file:
Then update as before:
Be aware that the software contained within this repository is NOT open source.
Adding Other Repositories
There are some reasons for which you might want to add non-Ubuntu repositories to your list of software sources. Caution: To avoid trouble with your sytem, only add repositories that are trustworthy and that are known to work on Ubuntu systems!
You can add custom software repositories by adding the apt repository line of your software source to the end of the sources.list file. It should look something like this:
Adding Launchpad PPA Repositories
Adding Launchpad PPA (Personal Package Archive) is possible conveniently via the command: add-apt-repository. This command is similar to «addrepo» on Debian.
The command updates your sources.list file or adds/edits files under sources.list.d/. Type man add-apt-repository for detailed help.
If a public key is required and available it is automatically downloaded and registered.
Should be installed by default. On older or minimal Ubuntu releases, you may have to install software-properties-common and/or python-software-properties first (sudo apt-get install python-software-properties)
Example: sudo add-apt-repository ppa:nhandler/ppa
Enabling Repositories with a (non-interactive) Script
This section seemed obsolete due to the add-apt-repository command, thus it has been removed.
Suggestions & Recommendations
It is always a good idea to back up configuration files like /etc/apt/sources.list before you begin editing. You can then revert your changes if needed.
If you decide to add other repositories to sources.list, make sure that the repository is meant to work (and known to work) with Ubuntu. Repositories that are not designed to work with your version of Ubuntu can introduce inconsistencies in your system and might force you to re-install. Also, make sure that you really need to add external repositories as the software package(s) you are looking for may already have been introduced into the official repositories!
Please keep in mind that it may not be legal (typically because of export restrictions) to enable some non-Ubuntu software repositories in some countries.
You may be asked enter a security key when adding a non-Ubuntu repository to your sources. See Managing Authentication Keys for instructions.
Источник
How to Update the List of Linux Repositories
When installing applications and programs on Linux there are several ways to do it. More advanced users can choose to download the source code from the developer’s website and compile it directly on their computer. Something very slow and impractical really. The most inexperienced users usually choose the easy way: search and download the binary (for example, the deb) and install it, from the package manager, by double clicking. As in Windows. And, thirdly, we have intermediate users who seek comfort and ease and make use of Linux repositories to download, install and update their programs.
What are Linux repositories?
Repositories are one of the best features that Linux has. A repository is a list of programs, usually always updated, that allows us to easily search and download all kinds of programs and tools in our distribution.
Thanks to the repositories we will be able to have a safe and reliable place from which to download software and the latest updates of all our programs. These programs will be installed without any dependency problems, and we can also update our entire program repertoire with a simple command.
The developers of the distros usually include their own repositories with useful programs. In addition, many developers maintain their own independent repositories to distribute their programs. Even any user can create and maintain their own repository, very useful, for example, to distribute software lists.
Different types of repositories in Ubuntu
When we install Ubuntu, the distro installs a series of repositories belonging to different channels:
- Main: the repository installed by default. It consists of free FOSS software that can be distributed freely and without restrictions.
- Universe: includes free and open source software, but cannot guarantee regular security updates.
- Multiverse: includes software that is from the FOSS. It must be the user who analyzes the licenses and decides whether or not to use these programs legally.
- Restricted: within this channel we can find closed source software. It is used, for example, to distribute NVIDIA drivers, among many others.
- Partner: includes proprietary software that has been packaged by Canonical.
And in addition to these repositories, we can also add third-party repositories to our Linux distro to install other software safely.
The steps we are going to see next have been done on Ubuntu, but they should be the same for any Debian-based distro.
How to add new repositories to the software list
To see the list of repositories that we have in our Ubuntu distro, what we must do is open a Terminal (Control + Alt + T) and execute the following command in this:
sudo gedit /etc/apt/sources.list
In case it does not work, or we do not have gedit installed in our distro, we can do it with the following, by going to the “nano” editor.
sudo nano /etc/apt/sources.list
As we will see, we will open a list with all the repositories that we have in our distro. Repositories (for example, deb http://en.archive.ubuntu.com/ubuntu/ bionic-updates main restricted) that start without # are those that are being used. On the other hand, those that appear at the beginning with a # are those that we have installed, but they are disabled.
If we want to add a new repo, we just have to add it, as follows, to the end of the text file:
- deb [arch = amd64] http://dl.google.com/linux/chrome/deb/ stable main
We save the changes and go. Of course, before updating the repositories and installing any program we must install the security keys of that repository. These are usually offered together with the PPA, and then we will see an example with the official Google Chrome repo.
Example to add Google Chrome repository from Terminal
To add a repository, or PPA, from Linux , we must do it as follows. The first thing will be to search the Internet for the repository we want to add. In the case of Google Chrome (this example), we can find it on the Google website .
In the terminal, we will execute the following command to add the keys of the official Google repositories to our Linux. Otherwise, the repositories software cannot be validated and will return an error:
wget -q -O – https://dl.google.com/linux/linux_signing_key.pub | sudo apt-key add –
Once the previous command has been executed, we can add the repository to the list of Ubuntu repositories. And we will do that with the following command:
sudo sh -c ‘echo “deb [arch = amd64] http://dl.google.com/linux/chrome/deb/ stable main” >> /etc/apt/sources.list.d/google.list’
Obviously, if we have added the repository from GEDIT as we explained in the previous step, this last command will not be necessary.
Now, first of all, we will have to update the list of Linux repositories to register in our system all the programs and to be able to download and install them with apt install.
How to update the list of Linux repositories
If we have already added the repositories we want to the list with the previous steps, or we simply want to update our software without adding new repositories, the process is much faster.
All we have left to do is open a Terminal (Control + Alt + T) in our Linux and execute the following two commands:
- sudo apt update (to update the software lists of the repositories).
- sudo apt upgrade (to download available packages).
When the process is finished, all the programs of our Linux, which have been installed through the repositories, will have been updated to their latest version.
We can now install the programs we want from the repositories of our Linux using apt install (for example: sudo apt install google-chrome).
Источник