Product SiteDocumentation Site

6.2. Команды aptitude, apt-get и apt

APT является большим проектом, в исходные планы которого входило создание графического интерфейса. Он основан на библиотеке, которая содержит приложение ядра, а apt-get является первым интерфейсом (основанным на режиме командной строки), который был разработан в рамках этого проекта. apt является вторым интерфейсом командной строки, предоставляемым APT, который устраняет некоторые ошибки проектирования apt-get.
Большое число графических интерфейсов появилось позже как внешние проекты: synaptic, aptitude (который включает и текстовый интерфейс, и графический — хоть и не завершённый до сих пор), wajig, и т.д. Наиболее рекомендуемый интерфейс, apt, мы будем использовать в примерах, приведённых в этом разделе. Обратите внимание, что apt-get и aptitude имеют весьма схожий синтаксис командной строки. В случае, когда существуют значительные различия между apt, apt-get и aptitude, эти различия будут разобраны более подробно.

6.2.1. Инициализация

При необходимости работы с APT должен быть обновлён список доступных пакетов; это просто сделать с помощью команды apt update. В зависимости от скорости вашего соединения, эта операция может занять достаточно времени, поскольку она включает загрузку определённого числа Packages/Sources/Translation-language-code файлов, которые постепенно становятся всё больше и больше в процессе разработки Debian (по меньшей мере 10 МБ данных для секции main). Конечно, установка с набора CD-ROM не требует никакой загрузки — в этом случае операция является очень быстрой.

6.2.2. Установка и удаление

С помощью APT пакеты могут быть добавлены или удалены из системы командами apt install пакет and apt remove пакет соответственно. В обоих случаях APT автоматически установит необходимые пакеты, от которого зависит данный, или удалит пакеты, которые зависят от удаляемого пакета. Команды apt purge пакет вызывают полное удаление — файлы настройки также будут удалены.
Если в файле sources.list упоминается несколько дистрибутивов, можно задать версию пакета для установки. Номер версии может быть запрошен, используя apt install packet= version, с указанием происхождения (Stable, Testing или Unstable) — apt install package/distribution — обычно предпочтительно. Используя эту команду можно вернуться к старой версии пакета (если например вы знаете, что она работает хорошо), при условии, что он по-прежнему доступен в одном из источников, на которые ссылается файл sources.list. В противном случае может помочь архив snapshot.debian.org (см. УГЛУБЛЯЕМСЯ Старые версии пакетов: snapshot.debian.org).

Пример 6.3. Установка unstable версии spamassassin

# apt install spamassassin/unstable

6.2.3. Обновление системы

Регулярные обновления рекомендуется, поскольку они включают последние обновления системы безопасности. Для обновления, используйте apt upgrade, apt-get upgrade или aptitude safe-upgrade (конечно после использования apt update). Эта команда ищет установленные пакеты, которые можно обновить без удаления других пакетов. Другими словами цель заключается в том, чтобы обеспечить наименее ограничительное возможность установки обновлений. Команда apt-get является немного более требовательной, чем aptitude или apt потому что она не будет устанавливать пакеты, которые не были установлены до этого.
apt обычно будет выбирать последние версии (за исключением пакетов из Experimental и stable-backports, которые игнорируются независимо от номера версии). Если вы указали Testing или Unstable в своем sources.list, apt upgrade переключит большую часть вашей системы со Stable на Testing или Unstable, что может быть не тем, чего вы ожидали.
To tell apt to use a specific distribution when searching for upgraded packages, you need to use the -t or --target-release option, followed by the name of the distribution you want (for example: apt -t stable upgrade). To avoid specifying this option every time you use apt, you can add APT::Default-Release "stable"; in the file /etc/apt/apt.conf.d/local.
For more important upgrades, such as the change from one major Debian version to the next, you need to use apt full-upgrade. With this instruction, apt will complete the upgrade even if it has to remove some obsolete packages or install new dependencies. This is also the command used by users who work daily with the Debian Unstable release and follow its evolution day by day. It is so simple that it hardly needs explanation: APT's reputation is based on this great functionality.
Unlike apt and aptitude, apt-get doesn't know the full-upgrade command. Instead, you should use apt-get dist-upgrade (”distribution upgrade”), the historical and well-known command that apt and aptitude also accept for the convenience of users who got used to it.

6.2.4. Configuration Options

Besides the configuration elements already mentioned, it is possible to configure certain aspects of APT by adding directives in a file of the /etc/apt/apt.conf.d/ directory. Remember for instance that it is possible for APT to tell dpkg to ignore file conflict errors by specifying DPkg::options { "--force-overwrite"; }.
If the Web can only be accessed through a proxy, add a line like Acquire::http::proxy "http://yourproxy:3128". For an FTP proxy, write Acquire::ftp::proxy "ftp://yourproxy". To discover more configuration options, read the apt.conf(5) manual page with the man apt.conf command (for details on manual pages, see Раздел 7.1.1, «Страницы руководств»).

6.2.5. Managing Package Priorities

One of the most important aspects in the configuration of APT is the management of the priorities associated with each package source. For instance, you might want to extend one distribution with one or two newer packages from Testing, Unstable or Experimental. It is possible to assign a priority to each available package (the same package can have several priorities depending on its version or the distribution providing it). These priorities will influence APT's behavior: for each package, it will always select the version with the highest priority (except if this version is older than the installed one and if its priority is less than 1000).
APT defines several default priorities. Each installed package version has a priority of 100. A non-installed version has a priority of 500 by default, but it can jump to 990 if it is part of the target release (defined with the -t command-line option or the APT::Default-Release configuration directive).
You can modify the priorities by adding entries in the /etc/apt/preferences file with the names of the affected packages, their version, their origin and their new priority.
APT will never install an older version of a package (that is, a package whose version number is lower than the one of the currently installed package) except if its priority is higher than 1000. APT will always install the highest priority package which follows this constraint. If two packages have the same priority, APT installs the newest one (whose version number is the highest). If two packages of same version have the same priority but differ in their content, APT installs the version that is not installed (this rule has been created to cover the case of a package update without the increment of the revision number, which is usually required).
In more concrete terms, a package whose priority is less than 0 will never be installed. A package with a priority ranging between 0 and 100 will only be installed if no other version of the package is already installed. With a priority between 100 and 500, the package will only be installed if there is no other newer version installed or available in another distribution. A package of priority between 501 and 990 will only be installed if there is no newer version installed or available in the target distribution. With a priority between 990 and 1000, the package will be installed except if the installed version is newer. A priority greater than 1000 will always lead to the installation of the package even if it forces APT to downgrade to an older version.
When APT checks /etc/apt/preferences, it first takes into account the most specific entries (often those specifying the concerned package), then the more generic ones (including for example all the packages of a distribution). If several generic entries exist, the first match is used. The available selection criteria include the package's name and the source providing it. Every package source is identified by the information contained in a Release file that APT downloads together with the Packages files. It specifies the origin (usually “Debian” for the packages of official mirrors, but it can also be a person's or an organization's name for third-party repositories). It also gives the name of the distribution (usually Stable, Testing, Unstable or Experimental for the standard distributions provided by Debian) together with its version (for example 8 for Debian Jessie). Let's have a look at its syntax through some realistic case studies of this mechanism.
Let's suppose that you only want to use packages from the stable version of Debian. Those provided in other versions should not be installed except if explicitly requested. You could write the following entries in the /etc/apt/preferences file:
Package: *
Pin: release a=stable
Pin-Priority: 900

Package: *
Pin: release o=Debian
Pin-Priority: -10
a=stable defines the name of the selected distribution. o=Debian limits the scope to packages whose origin is “Debian”.
Let's now assume that you have a server with several local programs depending on the version 5.14 of Perl and that you want to ensure that upgrades will not install another version of it. You could use this entry:
Package: perl
Pin: version 5.14*
Pin-Priority: 1001
The reference documentation for this configuration file is available in the manual page apt_preferences(5), which you can display with man apt_preferences.

6.2.6. Working with Several Distributions

apt being such a marvelous tool, it is tempting to pick packages coming from other distributions. For example, after having installed a Stable system, you might want to try out a software package available in Testing or Unstable without diverging too much from the system's initial state.
Even if you will occasionally encounter problems while mixing packages from different distributions, apt manages such coexistence very well and limits risks very effectively. The best way to proceed is to list all distributions used in /etc/apt/sources.list (some people always put the three distributions, but remember that Unstable is reserved for experienced users) and to define your reference distribution with the APT::Default-Release parameter (see Раздел 6.2.3, «Обновление системы»).
Let's suppose that Stable is your reference distribution but that Testing and Unstable are also listed in your sources.list file. In this case, you can use apt install package/testing to install a package from Testing. If the installation fails due to some unsatisfiable dependencies, let it solve those dependencies within Testing by adding the -t testing parameter. The same obviously applies to Unstable.
In this situation, upgrades (upgrade and full-upgrade) are done within Stable except for packages already upgraded to another distribution: those will follow updates available in the other distributions. We will explain this behavior with the help of the default priorities set by APT below. Do not hesitate to use apt-cache policy (see sidebar TIP apt-cache policy) to verify the given priorities.
Everything centers around the fact that APT only considers packages of higher or equal version than the installed one (assuming that /etc/apt/preferences has not been used to force priorities higher than 1000 for some packages).
Let's assume that you have installed version 1 of a first package from Stable and that version 2 and 3 are available respectively in Testing and Unstable. The installed version has a priority of 100 but the version available in Stable (the very same) has a priority of 990 (because it is part of the target release). Packages in Testing and Unstable have a priority of 500 (the default priority of a non-installed version). The winner is thus version 1 with a priority of 990. The package “stays in Stable”.
Let's take the example of another package whose version 2 has been installed from Testing. Version 1 is available in Stable and version 3 in Unstable. Version 1 (of priority 990 — thus lower than 1000) is discarded because it is lower than the installed version. This only leaves version 2 and 3, both of priority 500. Faced with this alternative, APT selects the newest version, the one from Unstable.If you don't want a package installed from Testing to migrate to Unstable, you have to assign a priority lower than 500 (490 for example) to packages coming from Unstable. You can modify /etc/apt/preferences to this effect:
Package: *
Pin: release a=unstable
Pin-Priority: 490

6.2.7. Tracking Automatically Installed Packages

One of the essential functionalities of apt is the tracking of packages installed only through dependencies. These packages are called “automatic”, and often include libraries for instance.
With this information, when packages are removed, the package managers can compute a list of automatic packages that are no longer needed (because there is no “manually installed” packages depending on them). apt-get autoremove will get rid of those packages. aptitude and apt do not have this command: the former because it removes them automatically as soon as they are identified, and the latter probably because the user should not have to manually run such a command. In all cases, the tools display a clear message listing the affected packages.
It is a good habit to mark as automatic any package that you don't need directly so that they are automatically removed when they aren't necessary anymore. apt-mark auto package will mark the given package as automatic whereas apt-mark manual package does the opposite. aptitude markauto and aptitude unmarkauto work in the same way although they offer more features for marking many packages at once (see Раздел 6.4.1, «aptitude»). The console-based interactive interface of aptitude also makes it easy to review the “automatic flag” on many packages.
People might want to know why an automatically installed package is present on the system. To get this information from the command line, you can use aptitude why package (apt and apt-get have no similar feature):
$ aptitude why python-debian
i   aptitude         Recommends apt-xapian-index         
i A apt-xapian-index Depends    python-debian (>= 0.1.15)