Перейти к содержимому

Как удалить пакет в debian

  • автор:

Глава 8. Инструменты управления пакетами Debian

8.1. Какие программы для управления пакетами имеются в Debian?

В Debian для управления пакетами имеется множество средств, от программ с графическими или текстовыми интерфейсами, до низкоуровневых утилит установки пакетов. Корректная работа всех доступных инструментов зависит от низкоуровневых утилит, и все они представлены здесь в порядке уменьшения уровня сложности.

Важно понимать, что высокоуровневые инструменты управления пакетами, такие как aptitude или synaptic , для управления пакетами используют apt , который, в свою очередь, использует dpkg для управления пакетами системы.

See Chapter 2. Debian package management of the Debian reference for more information about the Debian package management utilities. This document is available in various languages and formats, see the Debian Reference entry in the DDP Users’ Manuals overview.

8.1.1. dpkg

Это основная программа управления пакетами. dpkg может вызываться с многими параметрами. Наиболее часто используемые из них:

  • Показать список всех параметров: dpkg —help
  • Показать управляющий файл (и другую информацию) для указанного пакета: dpkg —info foo_VVV-RRR.deb
  • Установить пакет на жёсткий диск (т. е. распаковать и настроить): dpkg —install foo_VVV-RRR.deb
  • Распаковать архив Debian на жёсткий диск (но не настраивать): dpkg —unpack foo_VVV-RRR.deb . Учтите, что в результате данной операции пакет не обязан быть в рабочем состоянии; для правильной работы может потребоваться внесение изменений в некоторые файлы. Данная команда удаляет любую ранее установленную версию программы и запускает сценарий preinst указанного пакета (см. Раздел 7.6, «Зачем нужны сценарии preinst, postinst, prerm и postrm?»).
  • Настроить пакет, который был распакован ранее: dpkg —configure foo . Кроме всего прочего, эта команда запускает сценарий postinst указанного пакета (см. Раздел 7.6, «Зачем нужны сценарии preinst, postinst, prerm и postrm?»). Она также обновляет файлы, перечисленные в conffiles . Обратите внимание, что в качестве аргумента для параметра configure указывается имя пакета (т. е. foo), а не имя файла-архива Debian (т. е. foo_VVV-RRR.deb).
  • Распаковать файл с именем «blurf» (или группу файлов с именем «blurf*») из архива Debian: dpkg —fsys-tarfile foo_VVV-RRR.deb | tar -xf — ‘blurf*’
  • Удалить пакет (но не его файлы настроек): dpkg —remove foo
  • Удалить пакет (вместе с файлами настроек): dpkg —purge foo
  • Вывести состояние установки пакетов, содержащих в имени строку (или регулярное выражение) «foo*»: dpkg —list ‘foo*’

8.1.2. APT

APT is the Advanced Package Tool , an advanced interface to the Debian packaging system which provides the apt-get program. It provides commandline tools for searching and managing packages, and for querying information about them, as well as low-level access to all features of the libapt-pkg library. For more information, see the User’s Guide in /usr/share/doc/apt-doc/guide.html/index.html (you will have to install the apt-doc package).

Starting with Debian Jessie, some frequently used apt-get and apt-cache commands have an equivalent via the new apt binary. This means some popular commands like apt-get update , apt-get install , apt-get remove , apt-cache search , or apt-cache show now can also be called simply via apt , say apt update , apt install , apt remove , apt search , or apt show . The following is an overview of the old and new commands:

apt-get update -> apt update apt-get upgrade -> apt upgrade apt-get dist-upgrade -> apt full-upgrade apt-get install package -> apt install package apt-get remove package -> apt remove package apt-get autoremove -> apt autoremove apt-cache search string -> apt search string apt-cache policy package -> apt list -a package apt-cache show package -> apt show package apt-cache showpkg package -> apt show -a package

Инструмент apt совмещает функциональность apt-get и apt-cache, а также по умолчанию использует красивый цветной формат вывода, что очень удобно. Для использования в сценариях или для продвинутого использования предпочтительнее использовать apt-get (а иногда он просто необходим).

apt-get provides a simple way to retrieve and install packages from multiple sources using the command line. Unlike dpkg , apt-get does not understand .deb files, it works with the packages proper name and can only install .deb archives from a source specified in /etc/apt/sources.list . apt-get will call dpkg directly after downloading the .deb archives [5] from the configured sources.

Часто используемые команды apt-get :

  • To update the list of packages known by your system, you can run:
apt update
apt install foo
apt remove foo
apt source имя_пакета

Как удалить пакет в Debian?

Для решения этой проблемы нужно стереть информацию от этом пакете в файле /var/lib/dpkg/status.
Отредактируйте файл: sudo gedit /var/lib/dpkg/status
Нажмите на CTRL+F.
И ввести название проблемного пакета.
Удалить весь блок информации о пакете.
ВНИМАНИЕ: Не удалите ничего лишнего!
Сохраните файл.
Введите:
sudo apt-get -f install
Для полной надежности нужно удалить все файлы пакета.
Для этого надо установить и удалить этот пакет.

sudo apt-get install -y && sudo apt-get remove -y

Все проблема решена.

Ответ написан более трёх лет назад
Нравится 5 1 комментарий

mblp

apt-get remove не удалит все файлы пакета полностью как Вы утверждаете, для этого надо воспользоваться командой apt-get purge

Как удалить пакет в debian

Product SiteDocumentation Site

5.4. Работа с пакетами при помощи dpkg

dpkg is the base command for handling Debian packages on the system. If you have .deb packages, it is dpkg that allows installation or analysis of their contents. But this program only has a partial view of the Debian universe: it knows what is installed on the system, and whatever it is given on the command line, but knows nothing of the other available packages. As such, it will fail if a dependency is not met. Tools such as apt and aptitude , on the contrary, will create a list of dependencies to install everything as automatically as possible.

ЗАМЕТКА dpkg или apt ?

dpkg стоит рассматривать как низкоуровневый инструмент (движок), а apt — как инструмент, более близкий к пользователю, обходящий ограничения первого. Эти инструменты работают совместно, каждый со своей спецификой, заточенный под определённый круг задач.

5.4.1. Установка пакетов

dpkg — это, прежде всего, инструмент для установки уже доступных пакетов Debian (поскольку он ничего не загружает). Чтобы установить пакет, используется опция -i или —install .

Пример 5.2. Установка пакета при помощи dpkg

# dpkg -i man-db_2.9.4-2_amd64.deb (Reading database . 227466 files and directories currently installed.) Preparing to unpack man-db_2.9.4-2_amd64.deb . Unpacking man-db (2.9.4-2) over (2.8.5-2) . Setting up man-db (2.9.4-2) . Updating database of manual pages . man-db.service is a disabled or a static unit not running, not starting it. Processing triggers for mailcap (3.69) . 

We can see the different steps performed by dpkg ; we know, thus, at what point any error may have occurred. The installation can also be effected in two stages: first unpacking, then configuration. apt takes advantage of this, limiting the number of calls to dpkg (since each call is costly, due to loading of the database in memory, especially the list of already installed files).

Пример 5.3. Раздельная распаковка и настройка

# dpkg --unpack man-db_2.9.4-2_amd64.deb (Reading database . 227466 files and directories currently installed.) Preparing to unpack man-db_2.9.4-2_amd64.deb . Unpacking man-db (2.9.4-2) over (2.9.4-2) . Processing triggers for mailcap (3.69) . # dpkg --configure man-db Setting up man-db (2.9.4-2) . Updating database of manual pages . man-db.service is a disabled or a static unit not running, not starting it. 

Иногда dpkg по той или иной причине не может установить пакет и возвращает ошибку; если пользователь даёт указание проигнорировать эту ошибку, будет выдано лишь предупреждение; для этого существуют различные опции —force-* . Команда dpkg —force-help , или документация этой команды, выдаст полный список таких опций. Самой частой ошибкой, с которой вам придётся рано или поздно столкнуться, является конфликт файлов. Когда пакет содержит файл, который уже установлен другим пакетом, dpkg откажется устанавливать его, и мы получим такое сообщение:

Распаковывается пакет libgdm (из файла . /libgdm_3.8.3-2_amd64.deb) … dpkg: ошибка при обработке параметра /var/cache/apt/archives/libgdm_3.8.3-2_amd64.deb (--unpack): попытка перезаписать «/usr/bin/gdmflexiserver», который уже имеется в пакете gdm3 3.4.1-9

В этом случае, если вы считаете, что замена этого файла не представляет существенной опасности для стабильности вашей системы (зачастую это именно так), вы можете использовать опцию —force-overwrite , которая сообщит dpkg о необходимости проигнорировать эту ошибку и перезаписать файл.

While there are many available —force-* options, only —force-overwrite is likely to be used regularly. These options only exist for exceptional situations, rarely encountered in Debian Stable . It is better to leave them alone as much as possible in order to respect the rules imposed by the packaging mechanism. Do not forget, these rules ensure the consistency and stability of your system.

ВНИМАНИЕ Эффективное использование —force-*

Если вы не будете осторожны, использование опции —force-* может привести к тому, что команды APT перестанут работать. Некоторые из этих опций позволяют установить пакет с неудовлетворёнными зависимостями или при наличии конфликта. В результате согласованность системы с точки зрения зависимостей нарушается, и команды APT откажутся выполнять какие-либо действия кроме тех, которые вернут систему в согласованное состояние (это обычно сводится к установке отсутствующей зависимости или удалению проблемного пакета). Вот пример сообщения, сигнализирующего о такой ошибке, которое получено после установки новой версии rdesktop с игнорированием зависимости от более новой версии libc6 :

# apt full-upgrade [. ] Возможно, для исправления этих ошибок вы захотите воспользоваться «apt-get -f install». Пакеты, имеющие неудовлетворённые зависимости: rdesktop: Зависит от: libc6 (>= 2.5) но 2.3.6.ds1-13etch7 уже установлен E: Неудовлетворённые зависимости. Попытайтесь использовать -f.

Бесстрашные администраторы, уверенные в правильности своего анализа ситуации, могут проигнорировать предупреждение о проблеме зависимостями или конфликте, используя соответствующую опцию —force-* . В этом случае, если необходимо продолжать использовать apt или aptitude , нужно отредактировать /var/lib/dpkg/status и удалить/изменить зависимость или конфликт.

This manipulation is an ugly hack, and should never be used, except in the most extreme case of necessity. Quite frequently, a more fitting solution is to recompile the package that is causing the problem (see Раздел 15.1, «Пересборка пакета из его исходного кода») or use a new version (potentially corrected) from a repository such as the stable-backports one (see Раздел 6.1.2.4, «Стабильное ПО с обратной совместимостью»).

5.4.2. Удаление пакета

Invoking dpkg with the -r or —remove option, followed by the name of a package, removes that package. This removal is, however, not complete: all of the configuration files, maintainer scripts, log files (system logs) and other user data handled by the package remain. That way disabling the program is easily done by uninstalling it, and it is still possible to quickly reinstall it with the same configuration. To completely remove everything associated with a package, use the -P or —purge option, followed by the package name.

Пример 5.4. Полное удаление пакета debian-cd

# dpkg -r debian-cd (Reading database . 228705 files and directories currently installed.) Removing debian-cd (3.1.35) . # dpkg -P debian-cd (Reading database . 228049 files and directories currently installed.) Purging configuration files for debian-cd (3.1.35) . 

5.4.3. Запросы к базе данных dpkg и анализ файлов .deb

К ОСНОВАМ Синтаксис опций команд

Для большинста опций существуют «длинные» (одно или несколько слов, перед которыми ставится двойной дефис) и «короткие» варианты (одна буква, часто первая буква «длинного» варианта, после одного дефиса). Это соглашение так распространено, что уже является стандартом POSIX.

Before concluding this section, we will study dpkg options that query the internal database in order to obtain information. Giving first the long options and then corresponding short options (that will evidently take the same possible arguments) we cite

—listfiles package (or -L ), which lists the files installed by this package;
—search file (or -S ), which finds the package(s) containing the file;
—status package (or -s ), which displays the headers of an installed package;

—list (or -l ), which displays the list of packages known to the system and their installation status;

—contents file.deb (or -c ), which lists the files in the Debian package specified;
—info file.deb (or -I ), which displays the headers of this Debian package.

CAUTION dpkg —search and merged /usr

For various reasons, Debian now installs by default a few top-level directories as symlinks to their counterparts below /usr . For instance, /bin , /sbin and /lib are now symlinks to, respectively, /usr/bin , /usr/sbin and /usr/lib .

While this does provide desirable benefits, it can also be a source of confusion. For example, when you query dpkg which package is owning a given file, it will only be able to answer when you ask for its original path:

$ dpkg --search /bin/mount mount: /bin/mount $ dpkg --search /usr/bin/mount dpkg-query: no path found matching pattern /usr/bin/mount $ dpkg --search /bin/apt dpkg-query: no path found matching pattern /bin/apt $ dpkg --search /usr/bin/apt apt: /usr/bin/apt

This issue is currently tracked as bug #858331. There is also an ongoing discussion if the approach used so far is counterproductive.

Пример 5.5. Получение информации с помощью dpkg

$ dpkg -L base-passwd /. /usr /usr/sbin /usr/sbin/update-passwd /usr/share /usr/share/base-passwd /usr/share/base-passwd/group.master /usr/share/base-passwd/passwd.master /usr/share/doc /usr/share/doc/base-passwd /usr/share/doc/base-passwd/README /usr/share/doc/base-passwd/changelog.gz /usr/share/doc/base-passwd/copyright /usr/share/doc/base-passwd/users-and-groups.html /usr/share/doc/base-passwd/users-and-groups.txt.gz /usr/share/doc-base /usr/share/doc-base/users-and-groups /usr/share/lintian /usr/share/lintian/overrides /usr/share/lintian/overrides/base-passwd /usr/share/man /usr/share/man/de /usr/share/man/de/man8 /usr/share/man/de/man8/update-passwd.8.gz /usr/share/man/es /usr/share/man/es/man8 /usr/share/man/es/man8/update-passwd.8.gz /usr/share/man/fr /usr/share/man/fr/man8 /usr/share/man/fr/man8/update-passwd.8.gz /usr/share/man/ja /usr/share/man/ja/man8 /usr/share/man/ja/man8/update-passwd.8.gz /usr/share/man/man8 /usr/share/man/man8/update-passwd.8.gz /usr/share/man/pl /usr/share/man/pl/man8 /usr/share/man/pl/man8/update-passwd.8.gz /usr/share/man/ru /usr/share/man/ru/man8 /usr/share/man/ru/man8/update-passwd.8.gz $ dpkg -S /bin/date coreutils: /bin/date $ dpkg -s coreutils Package: coreutils Essential: yes Status: install ok installed Priority: required Section: utils Installed-Size: 17478 Maintainer: Michael Stone Architecture: amd64 Multi-Arch: foreign Source: coreutils (8.32-4) Version: 8.32-4+b1 Pre-Depends: libacl1 (>= 2.2.23), libattr1 (>= 1:2.4.44), libc6 (>= 2.28), libgmp10, libselinux1 (>= 3.1~) Description: GNU core utilities This package contains the basic file, shell and text manipulation utilities which are expected to exist on every operating system. . Specifically, this package includes: arch base64 basename cat chcon chgrp chmod chown chroot cksum comm cp csplit cut date dd df dir dircolors dirname du echo env expand expr factor false flock fmt fold groups head hostid id install join link ln logname ls md5sum mkdir mkfifo mknod mktemp mv nice nl nohup nproc numfmt od paste pathchk pinky pr printenv printf ptx pwd readlink realpath rm rmdir runcon sha*sum seq shred sleep sort split stat stty sum sync tac tail tee test timeout touch tr true truncate tsort tty uname unexpand uniq unlink users vdir wc who whoami yes Homepage: http://gnu.org/software/coreutils $ dpkg -l 'b*' Desired=Unknown/Install/Remove/Purge/Hold | Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend |/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad) ||/ Name Version Architecture Description +++-==========================-==============-============-================================== un backupninja  (no description available) un backuppc  (no description available) ii baloo-kf5 5.78.0-3 amd64 framework for searching and manag> un balsa  (no description available) ii baobab 3.38.0-1 amd64 GNOME disk usage analyzer un base  (no description available) un base-config  (no description available) ii base-files 11.1 amd64 Debian base system miscellaneous > ii base-passwd 3.5.51 amd64 Debian base system master passwor> ii bash 5.1-2+b1 amd64 GNU Bourne Again SHell [..] $ dpkg -c /var/cache/apt/archives/bash_5.1-3+b1_amd64.deb drwxr-xr-x root/root 0 2021-07-25 20:43 ./ drwxr-xr-x root/root 0 2021-07-25 20:43 ./bin/ -rwxr-xr-x root/root 1234376 2021-07-25 20:43 ./bin/bash drwxr-xr-x root/root 0 2021-07-25 20:43 ./etc/ -rw-r--r-- root/root 1994 2021-07-25 20:43 ./etc/bash.bashrc drwxr-xr-x root/root 0 2021-07-25 20:43 ./etc/skel/ -rw-r--r-- root/root 220 2021-07-25 20:43 ./etc/skel/.bash_logout -rw-r--r-- root/root 3526 2021-07-25 20:43 ./etc/skel/.bashrc -rw-r--r-- root/root 807 2021-07-25 20:43 ./etc/skel/.profile drwxr-xr-x root/root 0 2021-07-25 20:43 ./usr/ drwxr-xr-x root/root 0 2021-07-25 20:43 ./usr/bin/ -rwxr-xr-x root/root 6759 2021-07-25 20:43 ./usr/bin/bashbug -rwxr-xr-x root/root 14648 2021-07-25 20:43 ./usr/bin/clear_console drwxr-xr-x root/root 0 2021-07-25 20:43 ./usr/share/ drwxr-xr-x root/root 0 2021-07-25 20:43 ./usr/share/doc/ [..] $ dpkg -I /var/cache/apt/archives/bash_5.1-3+b1_amd64.deb new Debian package, version 2.0. size 1416600 bytes: control archive=7256 bytes. 77 bytes, 4 lines conffiles 1030 bytes, 27 lines control 4511 bytes, 64 lines md5sums 603 bytes, 31 lines * postinst #!/bin/bash 500 bytes, 25 lines * postrm #!/bin/sh 14536 bytes, 33 lines * preinst 289 bytes, 22 lines * prerm #!/bin/bash Package: bash Source: bash (5.1-3) Version: 5.1-3+b1 Architecture: amd64 Essential: yes Maintainer: Matthias Klose Installed-Size: 6470 Pre-Depends: libc6 (>= 2.25), libtinfo6 (>= 6) Depends: base-files (>= 2.1.12), debianutils (>= 2.15) Recommends: bash-completion (>= 20060301-0) Suggests: bash-doc Conflicts: bash-completion (  

УГЛУБЛЯЕМСЯ Сравнение версий

Так как dpkg является программой для работы с пакетами Debian, она, помимо всего прочего, содержит эталонную реализацию логики сравнения номеров версий. Поэтому у неё есть опция --compare-versions , используемая внешними программами (главным образом — сценариями настройки, запускаемыми самой dpkg ). Для этой опции требуются три параметра: номер версии, оператор сравнения и второй номер версии. Допустимые операторы сравнения — lt (строго меньше), le (меньше или равна), eq (равна), ne (не равна), ge (больше или равна), и gt (строго больше). Если сравнение верно, dpkg возвращает 0 (успех), если нет, то ненулевое значение (признак ошибки).

$ dpkg --compare-versions 1.2-3 gt 1.1-4 $ echo $? 0 $ dpkg --compare-versions 1.2-3 lt 1.1-4 $ echo $? 1 $ dpkg --compare-versions 2.6.0pre3-1 lt 2.6.0-1 $ echo $? 1

Обратите внимание на неожиданный сбой последнего сравнения: для dpkg буквы pre , обозначающие, как правило, предварительный выпуск, не имеет никакого особого значения, и буквенные символы сравниваются таким же образом, как и числа (a < b < c . ), в алфавитном порядке. Именно поэтому dpkg считает, что « 0pre3 » больше, чем « 0 ». При необходимости указать в номере версии, что она относится к предварительному выпуску, используется символ тильды « ~ »:

$ dpkg --compare-versions 2.6.0~pre3-1 lt 2.6.0-1 $ echo $? 0

5.4.4. Файл журнала dpkg

dpkg сохраняет журнал всех своих действий в /var/log/dpkg.log . Этот журнал чрезвычайно подробный: в нём задокументированы все этапы обработки пакетов dpkg . Этот журнал помогает не только отследить поведение dpkg, но и сохранить историю изменений в системе: можно найти точный момент, когда каждый пакет был установлен или обновлён, и эта информация может быть чрезвычайно полезной при выяснении причин изменения поведения системы в целом. Кроме того, ведётся запись информации обо всех версиях, и её легко сверить с changelog.Debian.gz из соответствующего пакета или с отчётами об ошибках онлайн.

5.4.5. Поддержка мультиархитектуры

Все пакеты Debian имеют поле Architecture в своих метаданных. Это поле может содержать либо значение « all » (для пакетов, которые не зависят от архитектуры), либо название конкретной архитектуры, для которой пакет предназначен (например «amd64», «armhf», …). В последнем случае dpkg по умолчанию допустит установку пакета только в том случае, если его архитектура соответствует архитектуре системы, возвращаемой dpkg --print-architecture .

Это ограничение гарантирует, что в системе не окажется двоичных файлов, скомпилированных для неправильной архитектуры. Всё было бы прекрасно, но на (некоторых) компьютерах можно запускать двоичные файлы для разных архитектур, нативно (к примеру, на системах «amd64» работают двоичные файлы для «i386») или через эмуляторы.

5.4.5.1. Включение мультиархитектуры

Поддержка мультиархитектуры dpkg позволяет определять «чужеродные архитектуры», которые могут быть установлены в данной системе. Это легко сделать с помощью dpkg --add-architecture , как показано в примере ниже. Существует и соответствующая команда dpkg --remove-architecture для отключения поддержки чужеродной архитектуры, но её можно использовать только в том случае, когда в системе не осталось ни одного пакета этой архитектуры.

# dpkg --print-architecture amd64 # dpkg --print-foreign-architectures # dpkg -i gcc-9-base_9.3.0-22_armhf.deb dpkg: error processing archive gcc-9-base_9.3.0-22_armhf.deb (--install): package architecture (armhf) does not match system (amd64) Errors were encountered while processing: gcc-9-base_9.3.0-22_armhf.deb # dpkg --add-architecture armhf # dpkg --add-architecture armel # dpkg --print-foreign-architectures armhf armel # dpkg -i gcc-9-base_9.3.0-22_armhf.deb (Reading database . 456367 files and directories currently installed.) Preparing to unpack gcc-9-base_9.3.0-22_armhf.deb . Unpacking gcc-9-base:armhf (9.3.0-22) . Setting up gcc-9-base:armhf (9.3.0-22) . # dpkg --remove-architecture armhf dpkg: error: cannot remove architecture 'armhf' currently in use by the database # dpkg --remove-architecture armel # dpkg --print-foreign-architectures armhf

ЗАМЕТКА Поддержка мультиархитектуры в APT

APT will automatically detect when dpkg has been configured to support foreign architectures and will start downloading the corresponding Packages files during its update process.

Чужеродные пакеты можно установить при помощи команды apt install пакет:архитектура .

НА ПРАКТИКЕ Использование собственнических двоичных файлов i386 в системах amd64

There are multiple use cases for multi-arch, but the most popular ones are the possibility to execute (sometimes proprietary) 32 bit binaries (i386) on 64 bit systems (amd64), and the possibility to cross-compile software for a platform or an architecture different from the host one.

5.4.5.2. Изменения, связанные с мультиархитектурой

To make multi-arch actually useful and usable, libraries had to be repackaged and moved to an architecture-specific directory so that multiple copies (targeting different architectures) can be installed alongside. Such updated packages contain the “ Multi-Arch: same ” header field to tell the packaging system that the various architectures of the package can be safely co-installed (and that those packages can only satisfy dependencies of packages of the same architecture). The most important libraries have been converted since the introduction of multi-arch in Debian 7 Wheezy , but there are many libraries that will likely never be converted unless someone specifically requests it (through a bug report for example).

$ dpkg -s gcc-9-base dpkg-query: error: --status needs a valid package name but 'gcc-9-base' is not: ambiguous package name 'gcc-9-base' with more than one installed instance Use --help for help about querying packages. $ dpkg -s gcc-9-base:amd64 gcc-9-base:armhf | grep ^Multi Multi-Arch: same Multi-Arch: same $ dpkg -L libgcc-s1:amd64 |grep .so /lib/x86_64-linux-gnu/libgcc_s.so.1 $ dpkg -S /usr/share/doc/gcc-9-base/copyright gcc-9-base:amd64, gcc-9-base:armhf: /usr/share/doc/gcc-9-base/copyright 

Стоит отметить, что для пакетов с полем Multi-Arch: same следует указывать имена с названием архитектуры, чтобы их можно было однозначно идентифицировать. Они также могут иметь общие файлы с другими экземплярами того же пакета; dpkg в этом случае гарантирует, что все пакеты имеют бит-в-бит идентичные общие файлы. Все экземпляры пакета должны быть одной и той же версии, так что и обновляться они должны вместе.

Поддержка мультиархитектуры также привносит некоторые интересные особенности в механизм обработки зависимосей. Для удовлетворения зависимости требуется либо пакет, помеченный « Multi-Arch: foreign », или пакет с такой же архитектурой (при разрешении зависимости архитектуро-независимые пакеты считаются имеющими ту же архитектуру, что и система). Зависимость может также быть ослаблена, чтобы позволить пакету любой архитектуры удовлетворять её, с помощью синтаксиса пакет:any , но но чужеродные пакеты могут удовлетворять такую зависимость, только если они помечены « Multi-Arch: allowed ».

Как удалить пакет в debian

Product SiteDocumentation Site

5.4. Manipulating Packages with dpkg

dpkg is the base command for handling Debian packages on the system. If you have .deb packages, it is dpkg that allows installation or analysis of their contents. But this program only has a partial view of the Debian universe: it knows what is installed on the system, and whatever it is given on the command line, but knows nothing of the other available packages. As such, it will fail if a dependency is not met. Tools such as apt and aptitude , on the contrary, will create a list of dependencies to install everything as automatically as possible.

NOTE dpkg or apt ?

dpkg should be seen as a system tool (backend), and apt as a tool closer to the user, which overcomes the limitations of the former. These tools work together, each one with its particularities, suited to specific tasks.

5.4.1. Installing Packages

dpkg is, above all, the tool for installing an already available Debian package (because it does not download anything). To do this, we use its -i or --install option.

Example 5.2. Installation of a package with dpkg

# dpkg -i man-db_2.9.4-2_amd64.deb (Reading database . 227466 files and directories currently installed.) Preparing to unpack man-db_2.9.4-2_amd64.deb . Unpacking man-db (2.9.4-2) over (2.8.5-2) . Setting up man-db (2.9.4-2) . Updating database of manual pages . man-db.service is a disabled or a static unit not running, not starting it. Processing triggers for mailcap (3.69) . 

We can see the different steps performed by dpkg ; we know, thus, at what point any error may have occurred. The installation can also be effected in two stages: first unpacking, then configuration. apt takes advantage of this, limiting the number of calls to dpkg (since each call is costly, due to loading of the database in memory, especially the list of already installed files).

Example 5.3. Separate unpacking and configuration

# dpkg --unpack man-db_2.9.4-2_amd64.deb (Reading database . 227466 files and directories currently installed.) Preparing to unpack man-db_2.9.4-2_amd64.deb . Unpacking man-db (2.9.4-2) over (2.9.4-2) . Processing triggers for mailcap (3.69) . # dpkg --configure man-db Setting up man-db (2.9.4-2) . Updating database of manual pages . man-db.service is a disabled or a static unit not running, not starting it. 

Sometimes dpkg will fail to install a package and return an error; if the user orders it to ignore this, it will only issue a warning; it is for this reason that we have the different --force-* options. The dpkg --force-help command, or documentation of this command, will give a complete list of these options. The most frequent error, which you are bound to encounter sooner or later, is a file collision. When a package contains a file that is already installed by another package, dpkg will refuse to install it. The following messages will then appear:

Unpacking libgdm (from . /libgdm_3.8.3-2_amd64.deb) . dpkg: error processing /var/cache/apt/archives/libgdm_3.8.3-2_amd64.deb (--unpack): trying to overwrite '/usr/bin/gdmflexiserver', which is also in package gdm3 3.4.1-9

In this case, if you think that replacing this file is not a significant risk to the stability of your system (which is usually the case), you can use the option --force-overwrite , which tells dpkg to ignore this error and overwrite the file.

While there are many available --force-* options, only --force-overwrite is likely to be used regularly. These options only exist for exceptional situations, rarely encountered in Debian Stable . It is better to leave them alone as much as possible in order to respect the rules imposed by the packaging mechanism. Do not forget, these rules ensure the consistency and stability of your system.

CAUTION Effective use of --force-*

If you are not careful, the use of an option --force-* can lead to a system where the APT family of commands will refuse to function. In effect, some of these options allow installation of a package when a dependency is not met, or when there is a conflict. The result is an inconsistent system from the point of view of dependencies, and the APT commands will refuse to execute any action except those that will bring the system back to a consistent state (this often consists of installing the missing dependency or removing a problematic package). This often results in a message like this one, obtained after installing a new version of rdesktop while ignoring its dependency on a newer version of the libc6 :

# apt full-upgrade [. ] You might want to run 'apt-get -f install' to correct these. The following packages have unmet dependencies: rdesktop: Depends: libc6 (>= 2.5) but 2.3.6.ds1-13etch7 is installed E: Unmet dependencies. Try using -f.

A courageous administrator who is certain of the correctness of their analysis may choose to ignore a dependency or conflict and use the corresponding --force-* option. In this case, if they want to be able to continue to use apt or aptitude , they must edit /var/lib/dpkg/status to delete/modify the dependency, or conflict, that they chose to override.

This manipulation is an ugly hack, and should never be used, except in the most extreme case of necessity. Quite frequently, a more fitting solution is to recompile the package that is causing the problem (see Section 15.1, “Rebuilding a Package from its Sources”) or use a new version (potentially corrected) from a repository such as the stable-backports one (see Section 6.1.2.4, “Stable Backports”).

5.4.2. Package Removal

Invoking dpkg with the -r or --remove option, followed by the name of a package, removes that package. This removal is, however, not complete: all of the configuration files, maintainer scripts, log files (system logs) and other user data handled by the package remain. That way disabling the program is easily done by uninstalling it, and it is still possible to quickly reinstall it with the same configuration. To completely remove everything associated with a package, use the -P or --purge option, followed by the package name.

Example 5.4. Removal and purge of the debian-cd package

# dpkg -r debian-cd (Reading database . 228705 files and directories currently installed.) Removing debian-cd (3.1.35) . # dpkg -P debian-cd (Reading database . 228049 files and directories currently installed.) Purging configuration files for debian-cd (3.1.35) . 

5.4.3. Querying dpkg 's Database and Inspecting .deb Files

BACK TO BASICS Option syntax

Most options are available in a “long” version (one or more relevant words, preceded by a double dash) and a “short” version (a single letter, often the initial of one word from the long version, and preceded by a single dash). This convention is so common that it is a POSIX standard.

Before concluding this section, we will study dpkg options that query the internal database in order to obtain information. Giving first the long options and then corresponding short options (that will evidently take the same possible arguments) we cite

--listfiles package (or -L ), which lists the files installed by this package;
--search file (or -S ), which finds the package(s) containing the file;
--status package (or -s ), which displays the headers of an installed package;

--list (or -l ), which displays the list of packages known to the system and their installation status;

--contents file.deb (or -c ), which lists the files in the Debian package specified;
--info file.deb (or -I ), which displays the headers of this Debian package.

CAUTION dpkg --search and merged /usr

For various reasons, Debian now installs by default a few top-level directories as symlinks to their counterparts below /usr . For instance, /bin , /sbin and /lib are now symlinks to, respectively, /usr/bin , /usr/sbin and /usr/lib .

While this does provide desirable benefits, it can also be a source of confusion. For example, when you query dpkg which package is owning a given file, it will only be able to answer when you ask for its original path:

$ dpkg --search /bin/mount mount: /bin/mount $ dpkg --search /usr/bin/mount dpkg-query: no path found matching pattern /usr/bin/mount $ dpkg --search /bin/apt dpkg-query: no path found matching pattern /bin/apt $ dpkg --search /usr/bin/apt apt: /usr/bin/apt

This issue is currently tracked as bug #858331. There is also an ongoing discussion if the approach used so far is counterproductive.

Example 5.5. Various queries with dpkg

$ dpkg -L base-passwd /. /usr /usr/sbin /usr/sbin/update-passwd /usr/share /usr/share/base-passwd /usr/share/base-passwd/group.master /usr/share/base-passwd/passwd.master /usr/share/doc /usr/share/doc/base-passwd /usr/share/doc/base-passwd/README /usr/share/doc/base-passwd/changelog.gz /usr/share/doc/base-passwd/copyright /usr/share/doc/base-passwd/users-and-groups.html /usr/share/doc/base-passwd/users-and-groups.txt.gz /usr/share/doc-base /usr/share/doc-base/users-and-groups /usr/share/lintian /usr/share/lintian/overrides /usr/share/lintian/overrides/base-passwd /usr/share/man /usr/share/man/de /usr/share/man/de/man8 /usr/share/man/de/man8/update-passwd.8.gz /usr/share/man/es /usr/share/man/es/man8 /usr/share/man/es/man8/update-passwd.8.gz /usr/share/man/fr /usr/share/man/fr/man8 /usr/share/man/fr/man8/update-passwd.8.gz /usr/share/man/ja /usr/share/man/ja/man8 /usr/share/man/ja/man8/update-passwd.8.gz /usr/share/man/man8 /usr/share/man/man8/update-passwd.8.gz /usr/share/man/pl /usr/share/man/pl/man8 /usr/share/man/pl/man8/update-passwd.8.gz /usr/share/man/ru /usr/share/man/ru/man8 /usr/share/man/ru/man8/update-passwd.8.gz $ dpkg -S /bin/date coreutils: /bin/date $ dpkg -s coreutils Package: coreutils Essential: yes Status: install ok installed Priority: required Section: utils Installed-Size: 17478 Maintainer: Michael Stone Architecture: amd64 Multi-Arch: foreign Source: coreutils (8.32-4) Version: 8.32-4+b1 Pre-Depends: libacl1 (>= 2.2.23), libattr1 (>= 1:2.4.44), libc6 (>= 2.28), libgmp10, libselinux1 (>= 3.1~) Description: GNU core utilities This package contains the basic file, shell and text manipulation utilities which are expected to exist on every operating system. . Specifically, this package includes: arch base64 basename cat chcon chgrp chmod chown chroot cksum comm cp csplit cut date dd df dir dircolors dirname du echo env expand expr factor false flock fmt fold groups head hostid id install join link ln logname ls md5sum mkdir mkfifo mknod mktemp mv nice nl nohup nproc numfmt od paste pathchk pinky pr printenv printf ptx pwd readlink realpath rm rmdir runcon sha*sum seq shred sleep sort split stat stty sum sync tac tail tee test timeout touch tr true truncate tsort tty uname unexpand uniq unlink users vdir wc who whoami yes Homepage: http://gnu.org/software/coreutils $ dpkg -l 'b*' Desired=Unknown/Install/Remove/Purge/Hold | Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend |/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad) ||/ Name Version Architecture Description +++-==========================-==============-============-================================== un backupninja  (no description available) un backuppc  (no description available) ii baloo-kf5 5.78.0-3 amd64 framework for searching and manag> un balsa  (no description available) ii baobab 3.38.0-1 amd64 GNOME disk usage analyzer un base  (no description available) un base-config  (no description available) ii base-files 11.1 amd64 Debian base system miscellaneous > ii base-passwd 3.5.51 amd64 Debian base system master passwor> ii bash 5.1-2+b1 amd64 GNU Bourne Again SHell [..] $ dpkg -c /var/cache/apt/archives/bash_5.1-3+b1_amd64.deb drwxr-xr-x root/root 0 2021-07-25 20:43 ./ drwxr-xr-x root/root 0 2021-07-25 20:43 ./bin/ -rwxr-xr-x root/root 1234376 2021-07-25 20:43 ./bin/bash drwxr-xr-x root/root 0 2021-07-25 20:43 ./etc/ -rw-r--r-- root/root 1994 2021-07-25 20:43 ./etc/bash.bashrc drwxr-xr-x root/root 0 2021-07-25 20:43 ./etc/skel/ -rw-r--r-- root/root 220 2021-07-25 20:43 ./etc/skel/.bash_logout -rw-r--r-- root/root 3526 2021-07-25 20:43 ./etc/skel/.bashrc -rw-r--r-- root/root 807 2021-07-25 20:43 ./etc/skel/.profile drwxr-xr-x root/root 0 2021-07-25 20:43 ./usr/ drwxr-xr-x root/root 0 2021-07-25 20:43 ./usr/bin/ -rwxr-xr-x root/root 6759 2021-07-25 20:43 ./usr/bin/bashbug -rwxr-xr-x root/root 14648 2021-07-25 20:43 ./usr/bin/clear_console drwxr-xr-x root/root 0 2021-07-25 20:43 ./usr/share/ drwxr-xr-x root/root 0 2021-07-25 20:43 ./usr/share/doc/ [..] $ dpkg -I /var/cache/apt/archives/bash_5.1-3+b1_amd64.deb new Debian package, version 2.0. size 1416600 bytes: control archive=7256 bytes. 77 bytes, 4 lines conffiles 1030 bytes, 27 lines control 4511 bytes, 64 lines md5sums 603 bytes, 31 lines * postinst #!/bin/bash 500 bytes, 25 lines * postrm #!/bin/sh 14536 bytes, 33 lines * preinst 289 bytes, 22 lines * prerm #!/bin/bash Package: bash Source: bash (5.1-3) Version: 5.1-3+b1 Architecture: amd64 Essential: yes Maintainer: Matthias Klose Installed-Size: 6470 Pre-Depends: libc6 (>= 2.25), libtinfo6 (>= 6) Depends: base-files (>= 2.1.12), debianutils (>= 2.15) Recommends: bash-completion (>= 20060301-0) Suggests: bash-doc Conflicts: bash-completion (  

GOING FURTHER Comparison of versions

Since dpkg is the program for handling Debian packages, it also provides the reference implementation of the logic of comparing version numbers. This is why it has a --compare-versions option, usable by external programs (especially configuration scripts executed by dpkg itself). This option requires three parameters: a version number, a comparison operator, and a second version number. The different possible operators are lt (strictly less than), le (less than or equal to), eq (equal), ne (not equal), ge (greater than or equal to), and gt (strictly greater than). If the comparison is correct, dpkg returns 0 (success); if not, it gives a non-zero return value (indicating failure).

$ dpkg --compare-versions 1.2-3 gt 1.1-4 $ echo $? 0 $ dpkg --compare-versions 1.2-3 lt 1.1-4 $ echo $? 1 $ dpkg --compare-versions 2.6.0pre3-1 lt 2.6.0-1 $ echo $? 1

Note the unexpected failure of the last comparison: for dpkg , pre , usually denoting a pre-release, has no particular meaning, and this program compares the alphabetic characters in the same way as the numbers (a < b < c . ), in alphabetical order. This is why it considers “ 0pre3 ” to be greater than “ 0 ”. When we want a package's version number to indicate that it is a pre-release, we use the tilde character, “ ~ ”:

$ dpkg --compare-versions 2.6.0~pre3-1 lt 2.6.0-1 $ echo $? 0

5.4.4. dpkg 's Log File

dpkg keeps a log of all of its actions in /var/log/dpkg.log . This log is extremely verbose, since it details every one of the stages through which packages handled by dpkg go. In addition to offering a way to track dpkg's behavior, it helps, above all, to keep a history of the development of the system: one can find the exact moment when each package has been installed or updated, and this information can be extremely useful in understanding a recent change in behavior. Additionally, all versions being recorded, it is easy to cross-check the information with the changelog.Debian.gz for packages in question, or even with online bug reports.

5.4.5. Multi-Arch Support

All Debian packages have an Architecture field in their control information. This field can contain either “ all ” (for packages that are architecture independent) or the name of the architecture that it targets (like “amd64”, “armhf”, …). In the latter case, by default, dpkg will only accept to install the package if its architecture matches the host's architecture as returned by dpkg --print-architecture .

This restriction ensures that users do not end up with binaries compiled for an incorrect architecture. Everything would be perfect except that (some) computers can run binaries for multiple architectures, either natively (an “amd64“ system can run “i386” binaries) or through emulators.

5.4.5.1. Enabling Multi-Arch

dpkg 's multi-arch support allows users to define “foreign architectures” that can be installed on the current system. This is simply done with dpkg --add-architecture like in the example below. There is a corresponding dpkg --remove-architecture to drop support of a foreign architecture, but it can only be used when no packages of this architecture remain.

# dpkg --print-architecture amd64 # dpkg --print-foreign-architectures # dpkg -i gcc-9-base_9.3.0-22_armhf.deb dpkg: error processing archive gcc-9-base_9.3.0-22_armhf.deb (--install): package architecture (armhf) does not match system (amd64) Errors were encountered while processing: gcc-9-base_9.3.0-22_armhf.deb # dpkg --add-architecture armhf # dpkg --add-architecture armel # dpkg --print-foreign-architectures armhf armel # dpkg -i gcc-9-base_9.3.0-22_armhf.deb (Reading database . 456367 files and directories currently installed.) Preparing to unpack gcc-9-base_9.3.0-22_armhf.deb . Unpacking gcc-9-base:armhf (9.3.0-22) . Setting up gcc-9-base:armhf (9.3.0-22) . # dpkg --remove-architecture armhf dpkg: error: cannot remove architecture 'armhf' currently in use by the database # dpkg --remove-architecture armel # dpkg --print-foreign-architectures armhf

NOTE APT's multi-arch support

APT will automatically detect when dpkg has been configured to support foreign architectures and will start downloading the corresponding Packages files during its update process.

Foreign packages can then be installed with apt install package:architecture .

IN PRACTICE Using proprietary i386 binaries on amd64

There are multiple use cases for multi-arch, but the most popular ones are the possibility to execute (sometimes proprietary) 32 bit binaries (i386) on 64 bit systems (amd64), and the possibility to cross-compile software for a platform or an architecture different from the host one.

5.4.5.2. Multi-Arch Related Changes

To make multi-arch actually useful and usable, libraries had to be repackaged and moved to an architecture-specific directory so that multiple copies (targeting different architectures) can be installed alongside. Such updated packages contain the “ Multi-Arch: same ” header field to tell the packaging system that the various architectures of the package can be safely co-installed (and that those packages can only satisfy dependencies of packages of the same architecture). The most important libraries have been converted since the introduction of multi-arch in Debian 7 Wheezy , but there are many libraries that will likely never be converted unless someone specifically requests it (through a bug report for example).

$ dpkg -s gcc-9-base dpkg-query: error: --status needs a valid package name but 'gcc-9-base' is not: ambiguous package name 'gcc-9-base' with more than one installed instance Use --help for help about querying packages. $ dpkg -s gcc-9-base:amd64 gcc-9-base:armhf | grep ^Multi Multi-Arch: same Multi-Arch: same $ dpkg -L libgcc-s1:amd64 |grep .so /lib/x86_64-linux-gnu/libgcc_s.so.1 $ dpkg -S /usr/share/doc/gcc-9-base/copyright gcc-9-base:amd64, gcc-9-base:armhf: /usr/share/doc/gcc-9-base/copyright 

It is worth noting that Multi-Arch: same packages must have their names qualified with their architecture to be unambiguously identifiable. They also have the possibility to share files with other instances of the same package; dpkg ensures that all packages have bit-for-bit identical files when they are shared. Last but not least, all instances of a package must have the same version. They must thus be upgraded together.

Multi-Arch support also brings some interesting challenges in the way dependencies are handled. Satisfying a dependency requires either a package marked “ Multi-Arch: foreign ” or a package whose architecture matches the one of the package declaring the dependency (in this dependency resolution process, architecture-independent packages are assumed to be of the same architecture than the host). A dependency can also be weakened to allow any architecture to fulfill it, with the package:any syntax, but foreign packages can only satisfy such a dependency if they are marked “ Multi-Arch: allowed ”.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *