Product SiteDocumentation Site

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

APT is a vast project, whose original plans included a graphical interface. It is based on a library which contains the core application, and apt-get is the first front end — command-line based — which was developed within the project. apt is a second command-line based front end provided by APT which overcomes some design mistakes of apt-get.
Both tools are built on top of the same library and are thus very close, but the default behavior of apt has been improved for interactive use and to actually do what most users expect. The APT developers reserve the right to change the public interface of this tool to further improve it. Conversely, the public interface of apt-get is well defined and will not change in any backwards incompatible way. It is thus the tool that you want to use when you need to script package installation requests.
Numerous other graphical interfaces then appeared as external projects: synaptic, aptitude (which includes both a text mode interface and a graphical one — even if not complete yet), wajig, etc. The most recommended interface, apt, is the one that we will use in the examples given in this section. Note, however, that apt-get and aptitude have a very similar command line syntax. When there are major differences between these three commands, these will be detailed.

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

For any work with APT, the list of available packages needs to be updated; this can be done simply through apt update. Depending on the speed of your connection and configuration, the operation can take a while, since it involves downloading a certain number of (usually compressed) files (Packages, Sources, Translation-language-code), which have gradually become bigger and bigger as Debian has developed (at least 10-16 MB of data for the main section). Of course, installing from a CD-ROM/DVD set does not require any downloading — in this case, the operation is very fast.

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

With APT, packages can be added or removed from the system, respectively with apt install package and apt remove package. In both cases, APT will automatically install the necessary dependencies or delete the packages which depend on the package that is being removed. The apt purge package command involves a complete uninstallation by deleting the configuration files as well.
If the file sources.list mentions several distributions, it is possible to give the version of the package to install. A specific version number can be requested with apt install package=version, but indicating its distribution of origin (Stable, Testing or Unstable) — with apt install package/distribution — is usually preferred. With this command, it is possible to go back to an older version of a package (if, for instance, you know that it works well), provided that it is still available in one of the sources referenced by the sources.list file. Otherwise the snapshot.debian.org archive can come to the rescue (see sidebar GOING FURTHER Old package versions: snapshot.debian.org and archive.debian.org).

Пример 6.4. Installation of the Unstable version of spamassassin

# apt install spamassassin/unstable
If the package to install has been made available to you under the form of a simple .deb file without any associated package repository, it is still possible to use APT to install it together with its dependencies (provided that the dependencies are available in the configured repositories) with a simple command: apt install ./path-to-the-package.deb. The leading ./ is important to make it clear that we are referring to a filename and not to the name of a package available in one of the repositories.

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.
Для более важных обновлений, таких как переход от одной основной версии Debian к следующей, вы должны использовать apt full-upgrade. С помощью этой инструкции apt выполнит обновление, при этом он удалит некоторые устаревшие пакеты и установит новые зависимости. Также эта команда используется пользователями, которые ежедневно работают с Unstable выпуском Debian и следят за его развитием день за днем. Это так просто, что вряд ли нуждается в объяснении: репутация APT основана на большой функциональности.
В отличие от apt и aptitude, apt-get не знает команды full-upgrade. Вместо этого, вы должны использовать apt-get dist-upgrade («обновление дистрибутива»). apt и aptitude также принимают эту историческую и хорошо известную команду для удобства тех пользователей, которые привыкли пользоваться ей.
The results of these operations are logged into /var/log/apt/history.log and /var/log/apt/term.log, whereas dpkg keeps its log in a file called /var/log/dpkg.log.

6.2.4. Параметры конфигурации

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 or /etc/apt/apt.conf itself. 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 (for details on manual pages, see Раздел 7.1.1, «Страницы руководств»).

6.2.5. Управление приоритетами пакетов

Один из многих важных аспектов в конфигурировании APT-а является управление приоритетами, ассоциироваными с каждым исходным пакетом. Для примера, ты можешь захотеть расширить дистибутив (к примеру стабильный - Stable) одним или двуми пакетами из других дистибутивов тестируемый (Testing) , нестабильный (Unstable) или экспериментальный (Experimental) . В этом случае имеется возможность определить приоритеты каждого доступного пакета (некоторые пакеты могут иметь свои приоритеты зависимостей к их версии или распространение -дистрибьютор предоставляет это). Те приоритеты будут влиять на поведение APT-а: для каждого пакета всегда будет выбираться версия с высочайшим приоритетом (кроме случаев, когда версия более старая, чем установлена в системе такая же и если его приоритет - меньше чем 1000).
APT определяет свои приоритеты по умолчанию. Каждая версия устанавливаемого пакета имеет приоритер 100. Не установленная версия имеет приоритет 500 по умолчанию, но это может прыгнуть (измениться) до 990 если это есть часть целевого (выпускаемого) релиза (определяется с -t опция командной строки или APT::Default-Release конфигурирование указание).
You can modify the priorities by adding entries in a file in /etc/apt/preferences.d/ or 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 (or it is explicitly requested by the user, see Раздел 6.2.2, «Установка и удаление»). 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
< 0
will never be installed,
1..99
will only be installed if no other version of the package is already installed,
100..499
will only be installed if there is no other newer version installed or available in another distribution,
500....989
will only be installed if there is no newer version installed or available in the target distribution,
990..1000
will be installed except if the installed version is newer,
> 1000
will always be installed, even if it forces APT to downgrade to an older version.
When APT checks /etc/apt/preferences and /etc/apt/preferences.d/, 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, 11 for Debian Bullseye). Let's have a look at its syntax through some realistic case studies of this mechanism.
Давайте предположим что вы хотите использовать пакеты только из стабильной (Stable) версии Debian-а. Пакеты из других версий (testing, unstable, experimental) не будут установлены, за исключением случаях - когда пользователь явно это запросит. Ты можешь записать следующие строчки в /etc/apt/preferences файл:
Package: * 
Pin: release a=stable
Pin-Priority: 900

Package: *
Pin: release o=Debian
Pin-Priority: -10
a=stable определяем имя выбранного дистибутива (stable-стабильный). o=Debian ограничиваем результаты поиска только пакетами чей оригинал (происхождение) есть “Debian”.
Let's now assume that you have a server with several local programs depending on the version 5.28 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.28*
Pin-Priority: 1001
To gain a better understanding of the mechanisms of priority and distribution or repository properties to pin do not hesitate to execute apt-cache policy to display the default priority associated with each package source, or apt-cache policy package to display the default priority for each available version and source of a package as explained in Раздел 6.3.1, «The apt-cache policy Command».
The reference documentation for the files /etc/apt/preferences and /etc/apt/preferences.d/ is available in the manual page apt_preferences(5), which you can display with man apt_preferences.

6.2.6. Работа с отдельными дистрибутивами

apt является замечательным инструментом. И это создает соблазн выискивать пакеты, приходящие из других дистибутивов. Для примера, после того, как вы установили Стабильный (Stable), вы можете захотеть попробовать программный пакет годный в других дистибутивах - Тестируемый (Testing) или Нестабильный (Unstable) без расхождения слишком много от исходного состояния системы.
Даже если вы будете изредка наталкиваться на трудности пока смешиваете пакеты из разных дистибутивов, apt управляет таким совместным сосуществованием очень хорошо и ограничивает риски очень эффективно. Лучший путь - как надо поступить в данном случае - это внести в список все дистибутивы, что вы желаете использовать, в /etc/apt/sources.list. Некоторые люди всегда помещают три дистибутива, но запомни, что Нестабильный (Unstable) предназначен для опытных пользователей. И дополнительно установить значение вашего предпочтения дистибутива с APT::Default-Release параметром (смотри Раздел 6.2.3, «Обновление системы»).
Давайте предположим, что Stable (Стабильный) является вашим рекомендованным (установленным) дистибутивом, однако строки Testing и Unstable также перечислены в вашем sources.list файле. В этом случае, вы можете использовать apt install пакет/testing для установки пакета из Testing. Если в процессе установки будут возникать ошибки - из-за неудовлетворенных зависимостей, дайте решение этих зависимостей внутри Testing через добавление параметра -t testing. Это очевидно, что аналогично надо поступить и по отношению к 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 (Раздел 6.3.1, «The apt-cache policy Command») to verify the given priorities.
Все концентрируется вокруг того факта, что APT только принимает во внимание пакеты выше или эквивалентной (равной) версии, которые установлены (беря на себя ответственность за то, что /etc/apt/preferences не будет использоваться для принудительного повышения приоритета выше значения 1000 для некоторых пакетов).
Давайте предположим, что вы установили версию 1 первого пакета из Стабильный (Stable) и что версии 2 и 3 есть доступны (в указанном порядке) в Тестируемый (Testing) and Нестабильный (Unstable). Установленная версия имеет приоритет 100, но доступные версии Stable (этот же пакет) имеет приоритет 990 (потому что это часть выпускаемого релиза - дистибутива). Пакеты в Testing and Unstable имеют приоритеты 500 (по умолчанию - приоритет неустановленной версии). Победитель таким образом будет версия 1 с приоритетом 990. Пакет - “расположенный в 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 the version in 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. Трассирование автоматически устнавливаемых пакетов (наблюдение)

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.
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 or apt autoremove will get rid of those packages. aptitude does not have this command because it removes them automatically as soon as they are identified. In all cases, the tools display a clear message listing the affected packages.
Это есть хорошая привычка помечать как автоматически устанавливаемые любые пакеты, в которых вы не нуждаетесь немедленно. Поэтому данные пакеты в дальнейшем автоматически будут удалены, когда в них отпадет необходимость. apt-mark auto package будет отмечать данный пакет как автоматически установленный несмотря на то, что apt-mark manual package делает противоположное. aptitude markauto и aptitude unmarkauto работают одинаковым образом, хотя они предлагают больше возможностей чтобы отметить много пакетов одновременно (see Раздел 6.5.1, «программа aptitude»). Не графический, а интерактивный интерфейс команды aptitude в консоле (терминале) также может быстро просмотреть у каких пакетов установлен флаг (отметка) “automatic flag”.
Люди могут хотеть знать почему автоматически установленные пакеты присутствуют в системе. Для получения это информации из командной строки, вы можете использовать aptitude why пакет (apt и apt- get имеют непохожие особенности):
$ aptitude why python3-debian
i   aptitude         Suggests apt-xapian-index
p   apt-xapian-index Depends  python3-debian (>= 0.1.14)

6.2.8. APT Patterns

Patterns allow you to specify complex search queries to select the packages you want to install or show. They were first implemented for aptitude (see Раздел 6.5, «Графические оболочки: aptitude, synaptic»), but now APT can also make use of them.
For example, we can use apt list ?automatic to list all the packages automatically installed. To find packages automatically installed no longer depended upon by manually installed packages the pattern ?garbage can be used.
Logic patterns can be combined with other packages to form more complex expressions. For instance, we could use a pattern like ?and(PATTERN, PATTERN). See apt-patterns(7) and glob(7) for all the patterns you can use and the complex expressions you can create with them.