Error failed to commit transaction invalid or corrupted package

This brief guide describes how to fix invalid or corrupted package (PGP signature) error in Arch Linux, EndeavourOS and Manjaro Linux.

This brief guide describes how to fix invalid or corrupted package (PGP signature) error in Arch Linux and its variants like EndeavourOS and Manjaro Linux.

Introduction

The other day I encountered with the following error when I tried to upgrade my Arch Linux system using command sudo pacman -Syu:

[...]
:: File /var/cache/pacman/pkg/libpsl-0.16.1-1-x86_64.pkg.tar.xz is corrupted (invalid or corrupted package (PGP signature)).
Do you want to delete it? [Y/n] y
error: failed to commit transaction (invalid or corrupted package)
Errors occurred, no packages were upgraded.

Then, I ran 'sudo pacman -Syyu' command, but still no luck. I kept getting the same error every time.

After a bit of search on Google and Arch Linux forums, I found that there are new keys in the archlinux-keyring package.

Fix «invalid or corrupted package (PGP signature)» error in Arch Linux

To solve «invalid or corrupted package (PGP signature)» error in Arch Linux, we need to update the archlinux-keyring package.

To do so, run:

$ sudo pacman -S archlinux-keyring

Sample output:

resolving dependencies...
looking for conflicting packages...

Packages (1) archlinux-keyring-20170104-1

Total Installed Size: 0.81 MiB
Net Upgrade Size: 0.04 MiB

:: Proceed with installation? [Y/n] y
(1/1) checking keys in keyring [######################] 100%
(1/1) checking package integrity [######################] 100%
(1/1) loading package files [######################] 100%
(1/1) checking for file conflicts [######################] 100%
(1/1) checking available disk space [######################] 100%
:: Processing package changes...
(1/1) upgrading archlinux-keyring [######################] 100%
==> Appending keys from archlinux.gpg...
gpg: marginals needed: 3 completes needed: 1 trust model: PGP
gpg: depth: 0 valid: 1 signed: 6 trust: 0-, 0q, 0n, 0m, 0f, 1u
gpg: depth: 1 valid: 6 signed: 69 trust: 0-, 0q, 0n, 6m, 0f, 0u
gpg: depth: 2 valid: 69 signed: 7 trust: 69-, 0q, 0n, 0m, 0f, 0u
gpg: next trustdb check due at 2017-09-07
==> Locally signing trusted keys in keyring...
 -> Locally signing key 0E8B644079F599DFC1DDC3973348882F6AC6A4C2...
 -> Locally signing key 684148BB25B49E986A4944C55184252D824B18E8...
 -> Locally signing key 91FFE0700E80619CEB73235CA88E23E377514E00...
 -> Locally signing key 44D4A033AC140143927397D47EFD567D4C7EA887...
 -> Locally signing key 27FFC4769E19F096D41D9265A04F9397CDFD6BB0...
 -> Locally signing key AB19265E5D7D20687D303246BA1DFB64FFF979E7...
==> Importing owner trust values...
==> Disabling revoked keys in keyring...
 -> Disabling key F5A361A3A13554B85E57DDDAAF7EF7873CFD4BB6...
 -> Disabling key 7FA647CD89891DEDC060287BB9113D1ED21E1A55...
 -> Disabling key D4DE5ABDE2A7287644EAC7E36D1A9E70E19DAA50...
 -> Disabling key BC1FBE4D2826A0B51E47ED62E2539214C6C11350...
 -> Disabling key 9515D8A8EAB88E49BB65EDBCE6B456CAF15447D5...
 -> Disabling key 4A8B17E20B88ACA61860009B5CED81B7C2E5C0D2...
 -> Disabling key 63F395DE2D6398BBE458F281F2DBB4931985A992...
 -> Disabling key 0B20CA1931F5DA3A70D0F8D2EA6836E1AB441196...
 -> Disabling key 8F76BEEA0289F9E1D3E229C05F946DED983D4366...
 -> Disabling key 66BD74A036D522F51DD70A3C7F2A16726521E06D...
 -> Disabling key 81D7F8241DB38BC759C80FCE3A726C6170E80477...
 -> Disabling key E7210A59715F6940CF9A4E36A001876699AD6E84...
==> Updating trust database...
gpg: next trustdb check due at 2017-09-07

The above command will update the new keys and disable the revoked keys in your Arch Linux system.

Again, I tried to upgrade my Arch Linux using command:

$ sudo pacman -Syu

This time the upgrade process went well without any issues.

22 comments

ph9214
November 12, 2017 — 9:03 pm

How do I add new ones like for mono-addins


Reply

AVL
September 29, 2018 — 8:58 pm

often problems- no key.
sudo pacman -Sy gnupg archlinux-keyring manjaro-keyring fast, important
sudo pacman -Syu big download/install
[clear is deleting operation !]
pacman-key –refresh-keys fast, important, impact


Reply

Manuel
December 9, 2018 — 12:19 am

Worked like a charm! Thank you very much.


Reply

keith sanby
January 7, 2019 — 11:17 pm

Worked for me THANKS


Reply

cereberus
February 15, 2019 — 4:01 am

I got this error out of the blue, your solution helped me to resolve it. Thank you!


Reply

Aaron Geoffrey Blomgren
March 1, 2019 — 11:34 am

OMG Thank you


Reply

sk
March 1, 2019 — 12:36 pm

You’re welcome.


Reply

Mike
April 9, 2019 — 12:02 pm

Thank you!


Reply

at
June 4, 2019 — 2:21 am

thanks x 100000


Reply

Peter
June 21, 2019 — 10:38 pm

Thanks!


Reply

elig0n
July 6, 2019 — 10:18 pm


Reply

Anonymous
July 31, 2019 — 9:22 am

Thanks Man…


Reply

longhairhippy
August 15, 2019 — 10:58 am

Seriously helpful! Thank you!


Reply

B
March 9, 2022 — 3:31 am

THANK YOU. My Arch system was doing this for TWO MONTHS and I just finally fixed it with this! 😀


Reply

Janko
April 29, 2022 — 2:22 pm

Working in 2022 for EndeavourOS as well, thank you a lot!


Reply

Teagan
May 30, 2022 — 11:46 pm

I couldn’t update it because of the missingcorrupted key


Reply

Doria
July 24, 2022 — 12:12 pm

After 1 hour trying different solutions for this problem I found this one and it worked! Updating the keyring did the trick for me.
Thanks a lot!


Reply

sk
July 24, 2022 — 1:20 pm

Glad it worked out for you. Happy to help.


Reply

Kgb
August 5, 2022 — 1:13 am

Thanks


Reply

kapil
October 28, 2022 — 8:43 pm

Thank you very much


Reply

eisGeist
December 22, 2022 — 12:51 pm

Dear SK, thank you so much!
I’m a Arch Linux newbee and your post solved the issue keeping me from successfully update my linux box.
Cheers!


Reply

Urias
December 23, 2022 — 4:35 am

You saved my day. I was having troubles installing python-docutils before I could compile a Wps Office package.


Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Содержание

  1. Ошибка при обновлении
  2. Arch Linux
  3. #1 2020-08-17 07:35:30
  4. [SOLVED] invalid or corrupted package (PGP sig.) — pacman can’t update
  5. #2 2020-08-17 07:58:50
  6. Re: [SOLVED] invalid or corrupted package (PGP sig.) — pacman can’t update
  7. #3 2020-08-17 08:10:52
  8. Re: [SOLVED] invalid or corrupted package (PGP sig.) — pacman can’t update
  9. #4 2020-08-17 08:31:05
  10. Re: [SOLVED] invalid or corrupted package (PGP sig.) — pacman can’t update
  11. #5 2020-08-17 08:37:08
  12. Re: [SOLVED] invalid or corrupted package (PGP sig.) — pacman can’t update
  13. pacman (Русский)/Package signing (Русский)
  14. Настройка
  15. Настройка pacman
  16. Инициализация связки ключей
  17. Управление связкой ключей
  18. Проверка мастер-ключей
  19. Добавление ключей разработчика
  20. Добавление неофициальных ключей
  21. Отладка при помощи gpg
  22. Решение проблем
  23. error: signature from xxx is invalid
  24. Удаление старых версий пакетов
  25. Сброс ключей
  26. Отключение проверки подписи
  27. Не удаётся импортировать ключи
  28. Обновление системы
  29. Смена сервера ключей
  30. Удаление кэшированных пакетов
  31. Не удаётся опознать подпись пакета
  32. Arch Linux
  33. #1 2013-12-25 04:30:20
  34. [SOLVED] Invalid or corrupted package (PGP signature)
  35. #2 2013-12-25 04:49:52
  36. Re: [SOLVED] Invalid or corrupted package (PGP signature)
  37. #3 2013-12-25 13:04:12
  38. Re: [SOLVED] Invalid or corrupted package (PGP signature)
  39. #4 2013-12-26 17:40:10
  40. Re: [SOLVED] Invalid or corrupted package (PGP signature)
  41. #5 2013-12-26 17:44:36
  42. Re: [SOLVED] Invalid or corrupted package (PGP signature)

Ошибка при обновлении

Признаюсь честно, у меня не Arch, у меня Manjaro, но может вы мне все-таки поможете.
Сразу после установки появилось сообщение, что готовы обновления. Я пытался обновить систему командой
Начинается обновление, но почти сразу появляется сообщение:

File /var/cache/pacman/pkg/udiskie-1.7.1-1-any.pkg.tar.xz is corrupted (invalid or corrupted package (PGP signature)).
Do you want to delete it? [Y/n]

error: failed to commit transaction (invalid or corrupted package)
Errors occurred, no packages were upgraded

# 5 лет, 2 месяца назад (отредактировано 5 лет, 2 месяца назад)

simulator-t
Что можно сделать в данной ситуации?

simulator-t
File /var/cache/pacman/pkg/udiskie-1.7.1-1-any.pkg.tar.xz is corrupted (invalid or corrupted package (PGP signature)).
Do you want to delete it? [Y/n]

# 5 лет, 2 месяца назад (отредактировано 5 лет, 2 месяца назад) Очистить кеш пакетного менеджера, обновить базу данных пакмана и установленные пакеты.
Перевод:
Если вылезает та же ошибка — сменить зеркало, повторить процедуру.

Да, если опять фейл — обновлять ключи. simulator-t, да, забыл, предложение Aivar, тоже исключать нельзя.

Вначале попробовал это
но не помогло.
Затем прошел по ссылке
Из ответа, который помог тамошним вопрошающим

sudo rm -r /etc/pacman.d/gnupg
sudo pacman -Sy gnupg archlinux-keyring manjaro-keyring
sudo pacman-key —init
sudo pacman-key —populate archlinux manjaro
sudo pacman-key —refresh-keys
sudo pacman -Sc
Try updating after that. If that does not work, the package might actually be corrupt.

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

Кстати, не по теме, но пользуясь случаем. В Arch при загрузке появляется какой-то drop-down terminal или это фишка Manjaro?

Удивляете. Арч будет таким, каким вы его сделаете. Кто знает, может у манджары guake в автозагрузке.

© 2006-2023, Русскоязычное сообщество Arch Linux.
Название и логотип Arch Linux ™ являются признанными торговыми марками.
Linux ® — зарегистрированная торговая марка Linus Torvalds и LMI.

Источник

Arch Linux

You are not logged in.

#1 2020-08-17 07:35:30

[SOLVED] invalid or corrupted package (PGP sig.) — pacman can’t update

It has been a month since I started this pc (work) (long vacation) and now I want to update it.

Pacman starts downloading 1099 packages, checks them, and then fails on:

I didn’t find any info about this on the arch news page and a directed search didn’t help either.
So sorry if I overlooked something, but I really don’t know where to go next.

Last edited by scippie (2020-08-17 08:37:37)

#2 2020-08-17 07:58:50

Re: [SOLVED] invalid or corrupted package (PGP sig.) — pacman can’t update

Update archlinux-keyring first.
This is one of the rare exceptions where a partial update is acceptable, iff directly followed by a full system upgrade:

Солідарність з Україною

Online

#3 2020-08-17 08:10:52

Re: [SOLVED] invalid or corrupted package (PGP sig.) — pacman can’t update

Yes, that fixed it, thanks.
Can you explain me what is happening? Why I need to do this? And how I can detect it in the future so that I don’t need to ask again?

#4 2020-08-17 08:31:05

Re: [SOLVED] invalid or corrupted package (PGP sig.) — pacman can’t update

Pacman’s keyring, which contains the public keys of the devs and TUs for package signature checking was out of date on your system.
Hence, packages signed with newer keys by the devs and TUs could not be verified by pacman.

Please also remember to mark this topic as SOLVED.

Last edited by schard (2020-08-17 08:32:58)

Солідарність з Україною

Online

#5 2020-08-17 08:37:08

Re: [SOLVED] invalid or corrupted package (PGP sig.) — pacman can’t update

Pacman’s keyring, which contains the public keys of the devs and TUs for package signature checking was out of date on your system.

But how do I ‘see’ that?
I’ve had keyring updates before, they went fine, so how could I know that this time, I should do it manually?

Please also remember to mark this topic as SOLVED.

Источник

pacman (Русский)/Package signing (Русский)

Для определения подлинности пакетов pacman использует ключи GnuPG и сеть доверия. Действующие мастер-ключи Arch Linux можно найти здесь. Ключи разработчиков и доверенных пользователей, которыми они подписывают свои пакеты, должны быть подписаны минимум тремя мастер-ключами. У каждого пользователя также есть свой уникальный PGP-ключ, сгенерированный при настройке утилиты pacman-key. Сеть доверия связывает ключи пользователей и мастер-ключи.

Примеры сетей доверия:

  • Пользовательские пакеты: обычный пользователь создаёт пакет и подписывает его своим локальным ключом.
  • Неофициальные пакеты: разработчик создаёт пакет и подписывает его ключом разработчика; обычный пользователь подписывает ключ разработчика локальным ключом.
  • Официальные пакеты: разработчик создаёт пакет и подписывает его ключом разработчика, подписанным мастер-ключами Arch Linux; обычный пользователь подписывает локальным ключом мастер-ключ и доверяет последнему поручиться за разработчика.

Настройка

Настройка pacman

Опция SigLevel в файле /etc/pacman.conf определяет необходимый для установки пакета уровень доверия. Подробную информацию о SigLevel можно найти в руководстве pacman.conf(5) § PACKAGE AND DATABASE SIGNATURE CHECKING и в комментариях в самом файле. Можно настроить проверку подписи как глобально, так для каждого репозитория в отдельности. Если задать SigLevel глобально в разделе [options] , то абсолютно все пакеты должны быть подписаны. Пакеты, которые вы собрали сами, необходимо подписывать с помощью утилиты makepkg.

Настройка по умолчанию позволяет устанавливать только те пакеты, которые подписаны доверенными ключами:

Параметр TrustedOnly используется в pacman по умолчанию, то есть настройка ниже аналогична предыдущей:

То же самое можно задать и для отдельного репозитория далее в файле конфигурации:

Здесь явно задаётся проверка подписи для пакетов из этого репозитория, но подпись базы данных не проверяется. Если задать здесь значение Optional , то для этого репозитория глобальное значение Required станет недействительно.

Инициализация связки ключей

Для инициализации связки ключей pacman выполните:

Для инициализации необходима энтропия. Чтобы сгенерировать больше энтропии, активно двигайте мышью, нажимайте случайные клавиши или выполняейте действия, связанные с диском (например, запустите в другой консоли ls -R / , find / -name foo или dd if=/dev/sda8 of=/dev/tty7 ). Если энтропия системы недостаточна, этот этап может занять часы; активная генерация энтропии ускорит процесс.

Генерируемая последовательность случайных чисел используется для создания связки ключей ( /etc/pacman.d/gnupg ) и GPG-ключа вашей системы.

Управление связкой ключей

Проверка мастер-ключей

Первоначальная настройка ключей выполняется командой:

При появлении запроса необходимо проверить подлинность мастер-ключей, поскольку они используются для подписи всех пакетов совместно с ключами разработчиков.

PGP-ключи довольно велики (2048 бит или больше), что делает их неудобными для восприятия людьми. Поэтому на основе ключа вычисляется 40-разрядная шестнадцатеричная хэш-сумма, по которой можно проверить его подлинность. Также нужно помнить, что последние восемь цифр хэш-суммы часто используют как имя или (короткий) ID ключа, а последние шестнадцать — как длинный ID ключа.

Добавление ключей разработчика

Ключи официальных разработчиков и доверенных пользователей подписываются мастер-ключами, так что вам не нужно использовать pacman-key, чтобы подписывать их самостоятельно. Когда pacman встречает в подписи пакета ключ, который не удаётся распознать, то предлагает скачать его с сервера ключей, указанного в параметре keyserver в файле /etc/pacman.d/gnupg/gpg.conf или в опции —keyserver командной строки. Перечень серверов ключей можно найти в Википедии.

Ключ разработчика нужно скачать всего единожды, после этого он будет использоваться для проверки любого пакета от этого разработчика.

Добавление неофициальных ключей

Этим способом можно добавить в связку ключей pacman свой ключ или включить подписанный неофициальный репозиторий.

В первую очередь получите у владельца ключа его ID ( keyid ). Добавьте полученный ключ в связку:

  1. Если ключ находится на сервере ключей, импортируйте его командой:
  2. Если у вас есть ссылка на файл ключа, скачайте его и выполните:

Всегда старайтесь проверять отпечаток — как мастер-ключей, так любых других ключей, которые вы собираетесь подписать:

Наконец, подпишите импортированный ключ локально:

Теперь этот ключ будет считаться доверенным.

Отладка при помощи gpg

При отладке доступ к связке ключей pacman можно получить напрямую с помощью gpg, например:

Решение проблем

error: signature from xxx is invalid

Эта ошибка связана с gpg. Она означает, что пакет на диске не сооветствует пакету, который был подписан его сопроводителем. Выяснить причину может быть непросто, но в большинстве случаев удаление файла и скачивание его заново решает проблему. И в любом случае, такое сообщение об ошибке свидетельствует о проблеме с gpg и ключами, которые используются для подписывания пакетов.

Ниже приведены три возможных решения. Если вы не уверены, что выбрать, попросите о помощи на форуме.

Удаление старых версий пакетов

Если постоянно возникает проблема с одним и тем же пакетом и вы уверены, что дело не в pacman-key, попробуйте удалить плохой пакет из кэша командой rm /var/cache/pacman/pkg/плохой_пакет* и скачайте его заново.

Удаление пакета из кэша может помочь при ошибке error: linux: signature from » » is invalid , произошедшей при обновлении. Такое сообщение не обязательно является свидетельством атаки «человек-посередине» — возможно, пакет просто был повреждён при скачивании.

Сброс ключей

Для сброса всех установленных в системе ключей необходимо удалить каталог /etc/pacman.d/gnupg . После этого выполните команды pacman-key —init и pacman-key —populate archlinux , чтобы добавить базовый набор ключей заново.

Отключение проверки подписи

Если подписи пакетов вас не интересуют, можно полностью отключить их проверку. Отредактируйте файл /etc/pacman.conf , раскомментировав следующую строку в разделе [options] :

Также необходимо закомментировать все параметры SigLevel в настройках репозиториев, потому что они имеют приоритет над глобальными настройками. В результате подпись пакетов проверяться не будет, как это было в pacman до четвертой версии. В этом случае устанавливать связку ключей при помощи pacman-key не нужно. Позже при необходимости можно будет включить проверку подписи пакетов обратно.

Не удаётся импортировать ключи

  • Устаревший пакет archlinux-keyring ;
  • Неправильные настройки даты и времени;
  • Интернет-провайдер блокирует порт, используемый для импорта PGP-ключей;
  • Кэш pacman содержит неподписанные пакеты, оставшиеся с предыдущих попыток;
  • Демон dirmngr не был правильно настроен;
  • Вы давно не обновлялись и gpg/pacman не справились с обновлением.

Давно не обновлявшийся пакет archlinux-keyring может привести к проблемам при синхронизации обновлений.

Ниже приведено несколько возможных решений.

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

Прежде всего попробуйте обновить систему.

Смена сервера ключей

Если вы предполагаете, что проблема связана с сервером ключей, то можно попробовать переключиться на сервер ключей Ubuntu. Отредактируйте файл /etc/pacman.d/gnupg/gpg.conf , изменив значение keyserver :

Удаление кэшированных пакетов

Возможно, кэш pacman в каталоге /var/cache/pacman/pkg/ содержит неподписанные пакеты. Очистите кеш вручную:

что удалит все пакеты в кэше, которые не были установлены.

Не удаётся опознать подпись пакета

Иногда при выполнении pacman -Syu вы можете столкнуться со следующей ошибкой:

Такое происходит, когда ключ создателя пакета отсутствует в локальной базе данных pacman-key или не является доверенным. Pacman не всегда имеет возможность проверить, был ли ключ скачан и является ли он доверенным, перед тем как продолжить обновление. Также возможно, что срок действия ключа истёк.

  • обновить ключи командой pacman-key —refresh-keys ;
  • вручную подписать недоверенный ключ локально;
  • сбросить ключи;
  • временно установить параметр SigLevel в значение TrustAll (не рекомендуется).

Источник

Arch Linux

You are not logged in.

#1 2013-12-25 04:30:20

[SOLVED] Invalid or corrupted package (PGP signature)

I’m making this post as a last resort to solving a problem I’m having with the installation of google chrome via pacman. I’ve scoured the forums and duck/google searched to see if I can find anything. Nothing seems to have helped. The integrity of the three packages below is failing.

I’ve tried (all together and separately):

Changing mirrors in /etc/pacman.d/mirrorlist

Updating signature list via

Purging cache and updating lists after the two above bullets with

Updating the hardware clock with

Changing the pacman.conf SigLevel default of «SigLevel = Required DatabaseOptional» to «SigLevel = Never» (I found that this instead converted my PGP signature error into a checksum error. So I don’t think this helps at all)

I’m at a total loss on what the issue may be. Some packages install fine, but chromium (along with firefox earlier) is giving me grief with the PGP signature being the problem, even though all signatures have been up-to-date.

/var/lib/pacman/sync looks normal with only community.db, core.db, and extra.db files (no part files or anything else)

Contents of my pacman.conf:

Last edited by digitally404 (2013-12-26 19:50:15)

#2 2013-12-25 04:49:52

Re: [SOLVED] Invalid or corrupted package (PGP signature)

What’s the output of ‘pacman -Syu —debug’?

#3 2013-12-25 13:04:12

Re: [SOLVED] Invalid or corrupted package (PGP signature)

Updating the hardware clock with

I don’t know if clock time would give these errors (though it could give related issues) but this command would not likely fix the issue if clock time was the problem — so this step doesn’t rule out clock issues.

Pacman uses the system time, not the hardware clock time. The command you issued sets the hardware clock to the system time — if a problem with the latter was suspected, this command wouldn’t change it.

The proper test would be to see that your system clock (including date) is accurate (matches the clock on your wall). The easiest way to do this is with [extra]/ntp.

«UNIX is simple and coherent. » — Dennis Ritchie, «GNU’s Not UNIX» — Richard Stallman

#4 2013-12-26 17:40:10

Re: [SOLVED] Invalid or corrupted package (PGP signature)

Thanks for the responses.

Output of ‘pacman -Syu —debug’ :

(Note: I can’t even upgrade my system now because of the PGP signature error.)

I think my system clock is fine because if I issue ‘$ date’ I get the correct date/time out.

#5 2013-12-26 17:44:36

Re: [SOLVED] Invalid or corrupted package (PGP signature)

Can you post the debug output when you answer

Источник

Related articles

  • Creating packages
  • Downgrading packages
  • pacman/Package signing
  • pacman/Pacnew and Pacsave
  • pacman/Restore local database
  • pacman/Rosetta
  • pacman/Tips and tricks
  • FAQ#Package management
  • System maintenance
  • Arch Build System
  • Official repositories
  • Arch User Repository

The pacman package manager is one of the major distinguishing features of Arch Linux. It combines a simple binary package format with an easy-to-use build system. The goal of pacman is to make it possible to easily manage packages, whether they are from the official repositories or the user’s own builds.

Pacman keeps the system up-to-date by synchronizing package lists with the master server. This server/client model also allows the user to download/install packages with a simple command, complete with all required dependencies.

Pacman is written in the C programming language and uses the bsdtar(1) tar format for packaging.

Tip: The pacman package contains tools such as makepkg and vercmp(8). Other useful tools such as pactree and checkupdates are found in pacman-contrib (formerly part of pacman). Run pacman -Ql pacman pacman-contrib | grep -E 'bin/.+' to see the full list.

Usage

What follows is just a small sample of the operations that pacman can perform. To read more examples, refer to pacman(8).

Tip: For those who have used other Linux distributions before, there is a helpful Pacman Rosetta article.

Installing packages

A package is an archive containing:

  • all of the (compiled) files of an application
  • metadata about the application, such as application name, version, dependencies, etc.
  • installation files and directives for pacman
  • (optionally) extra files to make your life easier, such as a start/stop script

Arch’s package manager pacman can install, update, and remove those packages. Using packages instead of compiling and installing programs yourself has various benefits:

  • easily updatable: pacman will update existing packages as soon as updates are available
  • dependency checks: pacman handles dependencies for you, you only need to specify the program and pacman installs it together with every other program it needs
  • clean removal: pacman has a list of every file in a package; this way, no files are unintentionally left behind when you decide to remove a package.

Note:

  • Packages often have optional dependencies which are packages that provide additional functionality to the application but not strictly required for running it. When installing a package, pacman will list a package’s optional dependencies, but they will not be found in pacman.log. Use the #Querying package databases command to view the optional dependencies of a package.
  • When installing a package which you require only as a (optional) dependency of some other package (i.e. not required by you explicitly), it is recommended to use the --asdeps option. For details, see the #Installation reason section.

Warning: When installing packages in Arch, avoid refreshing the package list without upgrading the system (for example, when a package is no longer found in the official repositories). In practice, do not run pacman -Sy package_name instead of pacman -Syu package_name, as this could lead to dependency issues. See System maintenance#Partial upgrades are unsupported and BBS#89328.

Installing specific packages

To install a single package or list of packages, including dependencies, issue the following command:

# pacman -S package_name1 package_name2 ...

To install a list of packages with regex (see this forum thread):

# pacman -S $(pacman -Ssq package_regex)

Sometimes there are multiple versions of a package in different repositories (e.g. extra and testing). To install the version from the extra repository in this example, the repository needs to be defined in front of the package name:

# pacman -S extra/package_name

To install a number of packages sharing similar patterns in their names, one can use curly brace expansion. For example:

# pacman -S plasma-{desktop,mediacenter,nm}

This can be expanded to however many levels needed:

# pacman -S plasma-{workspace{,-wallpapers},pa}
Virtual packages

A virtual package is a special package which does not exist by itself, but is provided by one or more other packages. Virtual packages allow other packages to not name a specific package as a dependency, in case there are several candidates. Virtual packages cannot be installed by their name, instead they become installed in your system when you have installed a package providing the virtual package.

Installing package groups

Some packages belong to a group of packages that can all be installed simultaneously. For example, issuing the command:

# pacman -S gnome

will prompt you to select the packages from the gnome group that you wish to install.

Sometimes a package group will contain a large amount of packages, and there may be only a few that you do or do not want to install. Instead of having to enter all the numbers except the ones you do not want, it is sometimes more convenient to select or exclude packages or ranges of packages with the following syntax:

Enter a selection (default=all): 1-10 15

which will select packages 1 through 10 and 15 for installation, or:

Enter a selection (default=all): ^5-8 ^2

which will select all packages except 5 through 8 and 2 for installation.

To see what packages belong to the gnome group, run:

# pacman -Sg gnome

Also visit https://archlinux.org/groups/ to see what package groups are available.

Note: If a package in the list is already installed on the system, it will be reinstalled even if it is already up-to-date. This behavior can be overridden with the --needed option.

Removing packages

To remove a single package, leaving all of its dependencies installed:

# pacman -R package_name

To remove a package and its dependencies which are not required by any other installed package:

# pacman -Rs package_name

Warning: When removing a group, such as gnome, this ignores the install reason of the packages in the group, because it acts as though each package in the group is listed separately. Install reason of dependencies is still respected.

The above may sometimes refuse to run when removing a group which contains otherwise needed packages. In this case try:

# pacman -Rsu package_name

To remove a package, its dependencies and all the packages that depend on the target package:

Warning: This operation is recursive, and must be used with care since it can remove many potentially needed packages.

# pacman -Rsc package_name

To remove a package, which is required by another package, without removing the dependent package:

# pacman -Rdd package_name

Pacman saves important configuration files when removing certain applications and names them with the extension: .pacsave. To prevent the creation of these backup files use the -n option:

# pacman -Rn package_name

Note: Pacman will not remove configurations that the application itself creates (for example «dotfiles» in the home directory).

Upgrading packages

Warning:

  • Users are expected to follow the guidance in the System maintenance#Upgrading the system section to upgrade their systems regularly and not blindly run the following command.
  • Arch only supports full system upgrades. See System maintenance#Partial upgrades are unsupported and #Installing packages for details.

Pacman can update all packages on the system with just one command. This could take quite a while depending on how up-to-date the system is. The following command synchronizes the repository databases and updates the system’s packages, excluding «local» packages that are not in the configured repositories:

# pacman -Syu

Querying package databases

Pacman queries the local package database with the -Q flag, the sync database with the -S flag and the files database with the -F flag. See pacman -Q --help, pacman -S --help and pacman -F --help for the respective suboptions of each flag.

Pacman can search for packages in the database, searching both in packages’ names and descriptions:

$ pacman -Ss string1 string2 ...

Sometimes, -s‘s builtin ERE (Extended Regular Expressions) can cause a lot of unwanted results, so it has to be limited to match the package name only; not the description nor any other field:

$ pacman -Ss '^vim-'

To search for already installed packages:

$ pacman -Qs string1 string2 ...

To search for package file names in remote packages:

$ pacman -F string1 string2 ...

To display extensive information about a given package:

$ pacman -Si package_name

For locally installed packages:

$ pacman -Qi package_name

Passing two -i flags will also display the list of backup files and their modification states:

$ pacman -Qii package_name

To retrieve a list of the files installed by a package:

$ pacman -Ql package_name

To retrieve a list of the files installed by a remote package:

$ pacman -Fl package_name

To verify the presence of the files installed by a package:

$ pacman -Qk package_name

Passing the k flag twice will perform a more thorough check.

To query the database to know which package a file in the file system belongs to:

$ pacman -Qo /path/to/file_name

To query the database to know which remote package a file belongs to:

$ pacman -F /path/to/file_name

To list all packages no longer required as dependencies (orphans):

$ pacman -Qdt

To list all packages explicitly installed and not required as dependencies:

$ pacman -Qet

See pacman/Tips and tricks for more examples.

Pactree

To view the dependency tree of a package:

$ pactree package_name

To view the dependant tree of a package, pass the reverse flag -r to pactree, or use whoneeds from pkgtoolsAUR.

Database structure

The pacman databases are normally located at /var/lib/pacman/sync. For each repository specified in /etc/pacman.conf, there will be a corresponding database file located there. Database files are gzipped tar archives containing one directory for each package, for example for the which package:

$ tree which-2.21-5
which-2.21-5
|-- desc

The desc file contains meta data such as the package description, dependencies, file size and MD5 hash.

Cleaning the package cache

Pacman stores its downloaded packages in /var/cache/pacman/pkg/ and does not remove the old or uninstalled versions automatically. This has some advantages:

  1. It allows to downgrade a package without the need to retrieve the previous version through other means, such as the Arch Linux Archive.
  2. A package that has been uninstalled can easily be reinstalled directly from the cache directory, not requiring a new download from the repository.

However, it is necessary to deliberately clean up the cache periodically to prevent the directory to grow indefinitely in size.

The paccache(8) script, provided within the pacman-contrib package, deletes all cached versions of installed and uninstalled packages, except for the most recent three, by default:

# paccache -r

Enable and start paccache.timer to discard unused packages weekly.

You can also define how many recent versions you want to keep. To retain only one past version use:

# paccache -rk1

Add the -u/--uninstalled switch to limit the action of paccache to uninstalled packages. For example to remove all cached versions of uninstalled packages, use the following:

# paccache -ruk0

See paccache -h for more options.

Pacman also has some built-in options to clean the cache and the leftover database files from repositories which are no longer listed in the configuration file /etc/pacman.conf. However pacman does not offer the possibility to keep a number of past versions and is therefore more aggressive than paccache default options.

To remove all the cached packages that are not currently installed, and the unused sync database, execute:

# pacman -Sc

To remove all files from the cache, use the clean switch twice, this is the most aggressive approach and will leave nothing in the cache directory:

# pacman -Scc

Warning: One should avoid deleting from the cache all past versions of installed packages and all uninstalled packages unless one desperately needs to free some disk space. This will prevent downgrading or reinstalling packages without downloading them again.

pkgcachecleanAUR and pacleanerAUR are two further alternatives to clean the cache.

Additional commands

Download a package without installing it:

# pacman -Sw package_name

Install a ‘local’ package that is not from a remote repository (e.g. the package is from the AUR):

# pacman -U /path/to/package/package_name-version.pkg.tar.zst

To keep a copy of the local package in pacman’s cache, use:

# pacman -U file:///path/to/package/package_name-version.pkg.tar.zst

Install a ‘remote’ package (not from a repository stated in pacman’s configuration files):

# pacman -U http://www.example.com/repo/example.pkg.tar.zst

To inhibit the -S, -U and -R actions, -p can be used.

Pacman always lists packages to be installed or removed and asks for permission before it takes action.

Installation reason

The pacman database organizes installed packages into two groups, according to installation reason:

  • explicitly-installed: packages that were literally passed to a generic pacman -S or -U command;
  • dependencies: packages that, despite never (in general) having been passed to a pacman installation command, were implicitly installed because they were required by packages explicitly installed.

When installing a package, it is possible to force its installation reason to dependency with:

# pacman -S --asdeps package_name

The command is normally used because explicitly-installed packages may offer optional packages, usually for non-essential features for which the user has discretion.

Tip: Installing optional dependencies with --asdeps will ensure that, if you remove orphans, pacman will also remove optional packages set this way.

When reinstalling a package, though, the current installation reason is preserved by default.

The list of explicitly-installed packages can be shown with pacman -Qe, while the complementary list of dependencies can be shown with pacman -Qd.

To change the installation reason of an already installed package, execute:

# pacman -D --asdeps package_name

Use --asexplicit to do the opposite operation.

Note: Using --asdeps and --asexplicit options when upgrading, such as with pacman -Syu package_name --asdeps, is discouraged. This would change the installation reason of not only the package being installed, but also the packages being upgraded.

Search for a package that contains a specific file

Merge-arrows-2.pngThis article or section is a candidate for merging with pacman/Tips and tricks.Merge-arrows-2.png

Notes: Looking at #Querying package databases this section duplicates but expands what is already covered there. Either this should be moved inside the previous section or merged as a pacman tip in the dedicated article, which is already linked (Discuss in Talk:Pacman)

Sync the files database:

# pacman -Fy

Search for a package containing a file, e.g.:

$ pacman -F pacman
core/pacman 5.2.1-1 (base base-devel) [installed]
    usr/bin/pacman
    usr/share/bash-completion/completions/pacman
extra/xscreensaver 5.43-1
    usr/lib/xscreensaver/pacman

Tip: You can enable/start pacman-filesdb-refresh.timer to refresh pacman files database weekly.

For advanced functionality, install pkgfile, which uses a separate database with all files and their associated packages.

What happens during package install/upgrade/removal

When successful, the workflow of a transaction follows five high-level steps plus pre/post transaction hooks:

  1. Initialize the transaction if there is not a database lock
  2. Choose which packages will be added or removed in the transaction
  3. Prepare the transaction, based on flags, by performing sanity checks on the sync databases, packages, and their dependencies
  4. Commit the transaction:
    1. When applicable, download packages (_alpm_sync_load)
    2. If pre-existing pacman PreTransaction hooks apply, they are executed.
    3. Packages are removed that are to-be-replaced, conflicting, or explicitly targeted to be removed
    4. If there are packages to add, then each package is committed
      1. If the package has an install script, its pre_install function is executed (or pre_upgrade or pre_remove in the case of an upgraded or removed package).
      2. Pacman deletes all the files from a pre-existing version of the package (in the case of an upgraded or removed package). However, files that were marked as configuration files in the package are kept (see /Pacnew and Pacsave).
      3. Pacman untars the package and dumps its files into the file system (in the case of an installed or upgraded package). Files that would overwrite kept, and manually modified, configuration files (see previous step), are stored with a new name (.pacnew).
      4. If the package has an install script, its post_install function is executed (or post_upgrade or post_remove in the case of an upgraded or removed package).
    5. If pacman PostTransaction hooks that exist at the end of the transaction apply, they are executed.
  5. Release the transaction and transaction resource (i.e. database lock)

Configuration

Pacman’s settings are located in /etc/pacman.conf: this is the place where the user configures the program to work in the desired manner. In-depth information about the configuration file can be found in pacman.conf(5).

General options

General options are in the [options] section. Read pacman.conf(5) or look in the default pacman.conf for information on what can be done here.

Comparing versions before updating

To see old and new versions of available packages, uncomment the «VerbosePkgLists» line in /etc/pacman.conf. The output of pacman -Syu will be like this:

Package (6)             Old Version  New Version  Net Change  Download Size

extra/libmariadbclient  10.1.9-4     10.1.10-1      0.03 MiB       4.35 MiB
extra/libpng            1.6.19-1     1.6.20-1       0.00 MiB       0.23 MiB
extra/mariadb           10.1.9-4     10.1.10-1      0.26 MiB      13.80 MiB

Enabling parallel downloads

Pacman 6.0 introduced the option to download packages in parallel. ParallelDownloads under [options] needs to be set to a positive integer in /etc/pacman.conf to use this feature (e.g., 5). Packages will otherwise be downloaded sequentially if this option is unset.

Skip package from being upgraded

Warning: Be careful in skipping packages, since partial upgrades are unsupported.

To have a specific package skipped when upgrading the system, add this line in the [options] section:

IgnorePkg=linux

For multiple packages use a space-separated list, or use additional IgnorePkg lines. Also, glob patterns can be used. If you want to skip packages just once, you can also use the --ignore option on the command-line — this time with a comma-separated list.

It will still be possible to upgrade the ignored packages using pacman -S: in this case pacman will remind you that the packages have been included in an IgnorePkg statement.

Skip package group from being upgraded

Warning: Be careful in skipping package groups, since partial upgrades are unsupported.

As with packages, skipping a whole package group is also possible:

IgnoreGroup=gnome

Skip file from being upgraded

All files listed with a NoUpgrade directive will never be touched during a package install/upgrade, and the new files will be installed with a .pacnew extension.

NoUpgrade=path/to/file

Multiple files can be specified like this:

NoUpgrade=path/to/file1 path/to/file2

Note: The path refers to files in the package archive. Therefore, do not include the leading slash.

Skip files from being installed to system

To always skip installation of specific directories list them under NoExtract. For example, to avoid installation of systemd units use this:

NoExtract=usr/lib/systemd/system/*

Later rules override previous ones, and you can negate a rule by prepending !.

Tip: Pacman issues warning messages about missing locales when updating a package for which locales have been cleared by localepurge or bleachbit. Commenting the CheckSpace option in pacman.conf suppresses such warnings, but consider that the space-checking functionality will be disabled for all packages.

Maintain several configuration files

If you have several configuration files (e.g. main configuration and configuration with testing repository enabled) and would have to share options between configurations you may use Include option declared in the configuration files, e.g.:

Include = /path/to/common/settings

where /path/to/common/settings file contains the same options for both configurations.

Hooks

Pacman can run pre- and post-transaction hooks from the /usr/share/libalpm/hooks/ directory; more directories can be specified with the HookDir option in pacman.conf, which defaults to /etc/pacman.d/hooks. Hook file names must be suffixed with .hook. Pacman hooks are not interactive.

Pacman hooks are used, for example, in combination with systemd-sysusers and systemd-tmpfiles to automatically create system users and files during the installation of packages. For example, tomcat8 specifies that it wants a system user called tomcat8 and certain directories owned by this user. The pacman hooks systemd-sysusers.hook and systemd-tmpfiles.hook invoke systemd-sysusers and systemd-tmpfiles when pacman determines that tomcat8 contains files specifying users and tmp files.

For more information on alpm hooks, see alpm-hooks(5).

Repositories and mirrors

Besides the special [options] section, each other [section] in pacman.conf defines a package repository to be used. A repository is a logical collection of packages, which are physically stored on one or more servers: for this reason each server is called a mirror for the repository.

Repositories are distinguished between official and unofficial. The order of repositories in the configuration file matters; repositories listed first will take precedence over those listed later in the file when packages in two repositories have identical names, regardless of version number. In order to use a repository after adding it, you will need to upgrade the whole system first.

Each repository section allows defining the list of its mirrors directly or in a dedicated external file through the Include directive; for example, the mirrors for the official repositories are included from /etc/pacman.d/mirrorlist. See the Mirrors article for mirror configuration.

Package cache directory

Pacman stores downloaded package files in cache, in a directory denoted by CacheDir in [options] section of pacman.conf (defaults to /var/cache/pacman/pkg/ if not set).

Cache directory may grow over time, even if keeping just the freshest versions of installed packages.

If you want to move that directory to some more convenient place, do one of the following:

  • Set the CacheDir option in pacman.conf to new directory. Remember to retain the trailing slash. This is the recommended solution.
  • Mount a dedicated partition or e.g. Btrfs subvolume in /var/cache/pacman/pkg/.
  • Bind-mount selected directory in /var/cache/pacman/pkg/.

Warning: Do not symlink the /var/cache/pacman/pkg/ directory to some other location. It will cause pacman to misbehave, especially when pacman attempts to update itself.

Package security

Pacman supports package signatures, which add an extra layer of security to the packages. The default configuration, SigLevel = Required DatabaseOptional, enables signature verification for all the packages on a global level. This can be overridden by per-repository SigLevel lines. For more details on package signing and signature verification, take a look at pacman-key.

Troubleshooting

«Failed to commit transaction (conflicting files)» error

If you see the following error: [1]

error: could not prepare transaction
error: failed to commit transaction (conflicting files)
package: /path/to/file exists in filesystem
Errors occurred, no packages were upgraded.

This is happening because pacman has detected a file conflict, and by design, will not overwrite files for you. This is by design, not a flaw.

If you know that you have not used another package manager like pip to install these files, the problem is usually trivial to solve (although to be sure, you should try to find out how these files got there in the first place). A safe way is to first check if another package owns the file (pacman -Qo /path/to/file). If the file is owned by another package, file a bug report. If the file is not owned by another package, you rename the file which ‘exists in filesystem’ and re-issue the update command. If all goes well, the file may then be removed. Importantly, do not do this if another package manager like pip believes it owns this file, because while this pacman transaction may now succeed, the other package manager will become deeply unhappy!

If you have, however, installed a program manually without using pacman, for example through make install, pip, or similar, you have to remove/uninstall this program with all of its files. See also Pacman tips#Identify files not owned by any package.

Every installed package provides a /var/lib/pacman/local/package-version/files file that contains metadata about this package. If this file gets corrupted, is empty or goes missing, it results in file exists in filesystem errors when trying to update the package. Such an error usually concerns only one package. Instead of manually renaming and later removing all the files that belong to the package in question, you may explicitly run pacman -S --overwrite glob package to force pacman to overwrite files that match glob.

«Failed to commit transaction (invalid or corrupted package)» error

Look for .part files (partially downloaded packages) in /var/cache/pacman/pkg/ and remove them (often caused by usage of a custom XferCommand in pacman.conf).

# find /var/cache/pacman/pkg/ -iname "*.part" -delete

That same error may also appear if archlinux-keyring is out-of-date, preventing pacman from verifying signatures. See Pacman/Package signing#Upgrade system regularly for the fix and how to avoid it in the future.

«Failed to init transaction (unable to lock database)» error

When pacman is about to alter the package database, for example installing a package, it creates a lock file at /var/lib/pacman/db.lck. This prevents another instance of pacman from trying to alter the package database at the same time.

If pacman is interrupted while changing the database, this stale lock file can remain. If you are certain that no instances of pacman are running then delete the lock file:

# rm /var/lib/pacman/db.lck

Tip: You can run fuser /var/lib/pacman/db.lck as root to verify if there is any process still using it.

Packages cannot be retrieved on installation

This error manifests as Not found in sync db, Target not found or Failed retrieving file.

Firstly, ensure the package actually exists. If certain the package exists, your package list may be out-of-date. Try running pacman -Syu to force a refresh of all package lists and upgrade. Also make sure the selected mirrors are up-to-date and repositories are correctly configured.

It could also be that the repository containing the package is not enabled on your system, e.g. the package could be in the multilib repository, but multilib is not enabled in your pacman.conf.

See also FAQ#Why is there only a single version of each shared library in the official repositories?.

Pacman crashes during an upgrade

In the case that pacman crashes with a «database write» error while removing packages, and reinstalling or upgrading packages fails thereafter, do the following:

  1. Boot using the Arch installation media. Preferably use a recent media so that the pacman version matches/is newer than the system.
  2. Mount the system’s root filesystem, e.g., mount /dev/sdaX /mnt as root, and check the mount has sufficient space with df -h
  3. Mount the proc, sys and dev filesystems as well: mount -t proc proc /mnt/proc; mount --rbind /sys /mnt/sys; mount --rbind /dev /mnt/dev
  4. If the system uses default database and directory locations, you can now update the system’s pacman database and upgrade it via pacman --sysroot /mnt -Syu as root.
    • Alternatively, if you cannot update/upgrade, refer to Pacman/Tips and tricks#Reinstalling all packages.
  5. After the upgrade, one way to double-check for not upgraded but still broken packages: find /mnt/usr/lib -size 0
  6. Followed by a re-install of any still broken package via pacman --sysroot /mnt -S package.

pacman: command not found

If /var/cache/pacman/pkg is a symlink, pacman will try to make a directory instead and thus remove this symlink during self-upgrade. This will cause the update to fail. As a result, /usr/bin/pacman and other contents of the pacman package will be missing.

Never symlink /var/cache/pacman/pkg because it is controlled by pacman. Use the CacheDir option or a bind mount instead; see #Package cache directory.

If you have already encountered this problem and broke your system, you can manually extract /usr contents from the package to restore pacman and then reinstall it properly; see FS#73306 and related forum thread for details.

Manually reinstalling pacman

Using pacman-static

pacman-staticAUR is a statically compiled version of pacman, so it will be able to run even when the libraries on the system are not working. This can also come in handy when a partial upgrade was performed and pacman can not run anymore.

The pinned comment and the PKGBUILD provides a way to directly download the binary, which can be used to reinstall pacman or to upgrade the entire system in case of partial upgrades.

Using an external pacman

If even pacman-static does not work, it is possible to recover using an external pacman. One of the easiest methods to do so is by using the archiso and simply using --sysroot or --root to specify the mount point. See Chroot#Using chroot on how to mount the necessary filesystems required by --sysroot.

Warning: It is extremely easy to break your system even worse using this approach. Use this only as a last resort if the method from #Pacman crashes during an upgrade is not an option.

Even if pacman is terribly broken, you can fix it manually by downloading the latest packages and extracting them to the correct locations. The rough steps to perform are:

  1. Determine the pacman dependencies to install
  2. Download each package from a mirror of your choice
  3. Extract each package to root
  4. Reinstall these packages with pacman -S --overwrite to update the package database accordingly
  5. Do a full system upgrade

If you have a healthy Arch system on hand, you can see the full list of dependencies with:

$ pacman -Q $(pactree -u pacman)

But you may only need to update a few of them depending on your issue. An example of extracting a package is

# tar -xvpwf package.tar.zst -C / --exclude .PKGINFO --exclude .INSTALL --exclude .MTREE --exclude .BUILDINFO

Note the use of the w flag for interactive mode. Running non-interactively is very risky since you might end up overwriting an important file. Also take care to extract packages in the correct order (i.e. dependencies first). This forum post contains an example of this process where only a couple pacman dependencies are broken.

«Unable to find root device» error after rebooting

Most likely the initramfs became corrupted during a kernel update (improper use of pacman’s --overwrite option can be a cause). There are two options; first, try the Fallback entry.

Tip: In case you removed the Fallback entry, you can always press the Tab key when the boot loader menu shows up (for Syslinux) or e (for GRUB or systemd-boot), rename it initramfs-linux-fallback.img and press Enter or b (depending on your boot loader) to boot with the new parameters.

Once the system starts, run this command (for the stock linux kernel) either from the console or from a terminal to rebuild the initramfs image:

# mkinitcpio -p linux

If that does not work, from a current Arch release (CD/DVD or USB stick), mount your root and boot partitions to /mnt and /mnt/boot, respectively. Then chroot using arch-chroot:

# arch-chroot /mnt
# pacman -Syu mkinitcpio systemd linux

Note:

  • If you do not have a current release or if you only have some other «live» Linux distribution laying around, you can chroot using the old fashioned way. Obviously, there will be more typing than simply running the arch-chroot script.
  • If pacman fails with Could not resolve host, please check your internet connection.
  • If you cannot enter the arch-chroot or chroot environment but need to re-install packages, you can use the command pacman --sysroot /mnt -Syu foo bar to use pacman on your root partition.

Reinstalling the kernel (the linux package) will automatically re-generate the initramfs image with mkinitcpio -p linux. There is no need to do this separately.

Afterwards, it is recommended that you run exit, umount /mnt/{boot,} and reboot.

«Warning: current locale is invalid; using default «C» locale» error

As the error message says, your locale is not correctly configured. See Locale.

Pacman does not honor proxy settings

Make sure that the relevant environment variables ($http_proxy, $ftp_proxy etc.) are set up. If you use pacman with sudo, you need to configure sudo to pass these environment variables to pacman. Also, ensure the configuration of dirmngr has honor-http-proxy in /etc/pacman.d/gnupg/dirmngr.conf to honor the proxy when refreshing the keys.

How do I reinstall all packages, retaining information on whether something was explicitly installed or as a dependency?

To reinstall all the native packages: pacman -Qnq | pacman -S - or pacman -S $(pacman -Qnq) (the -S option preserves the installation reason by default).

You will then need to reinstall all the foreign packages, which can be listed with pacman -Qmq.

«Cannot open shared object file» error

It looks like previous pacman transaction removed or corrupted shared libraries needed for pacman itself.

To recover from this situation, you need to unpack required libraries to your filesystem manually. First find what package contains the missed library and then locate it in the pacman cache (/var/cache/pacman/pkg/). Unpack required shared library to the filesystem. This will allow to run pacman.

Now you need to reinstall the broken package. Note that you need to use --overwrite flag as you just unpacked system files and pacman does not know about it. Pacman will correctly replace our shared library file with one from package.

That’s it. Update the rest of the system.

Freeze of package downloads

Some issues have been reported regarding network problems that prevent pacman from updating/synchronizing repositories. [2] [3] When installing Arch Linux natively, these issues have been resolved by replacing the default pacman file downloader with an alternative (see Improve pacman performance for more details). When installing Arch Linux as a guest OS in VirtualBox, this issue has also been addressed by using Host interface instead of NAT in the machine properties.

Failed retrieving file ‘core.db’ from mirror

If you receive this error message with correct mirrors, try setting a different name server.

error: ‘local-package.pkg.tar’: permission denied

If you want to install a package on an sshfs mount using pacman -U and receive this error, move the package to a local directory and try to install again.

error: could not determine cachedir mount point /var/cache/pacman/pkg

Upon executing, e.g., pacman -Syu inside a chroot environment an error is encountered:

error: could not determine cachedir mount point /var/cache/pacman/pkg
error: failed to commit transaction (not enough free disk space)

This is frequently caused by the chroot directory not being a mountpoint when the chroot is entered. See the note at Install Arch Linux from existing Linux#Downloading basic tools for a solution, and arch-chroot(8) for an explanation and an example of using bind mounting to make the chroot directory a mountpoint.

error: GPGME error: No data

If you are unable to update packages and receive this error, try rm -r /var/lib/pacman/sync/ before attempting to update.

See also

  • Pacman Home Page
  • libalpm(3)
  • pacman(8)
  • pacman.conf(5)
  • repo-add(8)

#
5 лет, 3 месяца назад

Темы:

2

Сообщения:

5

Участник с: 14 января 2017

Признаюсь честно, у меня не Arch, у меня Manjaro, но может вы мне все-таки поможете.
Сразу после установки появилось сообщение, что готовы обновления. Я пытался обновить систему командой

pacman -Su

Начинается обновление, но почти сразу появляется сообщение:

File /var/cache/pacman/pkg/udiskie-1.7.1-1-any.pkg.tar.xz is corrupted (invalid or corrupted package (PGP signature)).
Do you want to delete it? [Y/n]

Я нажимаю y и появляется сообщение об ошибке:

error: failed to commit transaction (invalid or corrupted package)
Errors occurred, no packages were upgraded

И на этом все заканчивается. Что можно сделать в данной ситуации?

vasek

#
5 лет, 3 месяца назад

(отредактировано

5 лет, 3 месяца назад)

Темы:

47

Сообщения:

11417

Участник с: 17 февраля 2013

simulator-t
Что можно сделать в данной ситуации?

Судя по сообщению

simulator-t
File /var/cache/pacman/pkg/udiskie-1.7.1-1-any.pkg.tar.xz is corrupted (invalid or corrupted package (PGP signature)).
Do you want to delete it? [Y/n]

Есть два пути
1. Чтобы не заморачиваться пока с пакетом udiskie, с которым проблемы, обновись без этого пакета, заодно узнаешь — в одном ли в этом пакете дело.
pacman -Syu —ignore udiskie
Если обновление пройдет нормально, без ошибок, пробуй удалить этот пакет полностью, а потом по-новой установить. Не получиться, переходи к п.2.
2. Сразу заняться решением проблемы. Гугли по ошибке. Наиболее вероятное решениеобновить ключи
— для Manjaro — читай свою Wiki + почитай Ваш топик
— для ArchLinux — читай нашу Wiki

Ошибки не исчезают с опытом — они просто умнеют

Aivar

#
5 лет, 3 месяца назад

(отредактировано

5 лет, 3 месяца назад)

Темы:

4

Сообщения:

6897

Участник с: 17 февраля 2011

Очистить кеш пакетного менеджера, обновить базу данных пакмана и установленные пакеты.
Перевод:

# pacman -Scc
# pacman -Syyu

Если вылезает та же ошибка — сменить зеркало, повторить процедуру.

Да, если опять фейл — обновлять ключи.

vasek

#
5 лет, 3 месяца назад

Темы:

47

Сообщения:

11417

Участник с: 17 февраля 2013

simulator-t, да, забыл, предложение Aivar, тоже исключать нельзя.

Ошибки не исчезают с опытом — они просто умнеют

simulator-t

#
5 лет, 3 месяца назад

Темы:

2

Сообщения:

5

Участник с: 14 января 2017

Вначале попробовал это

# pacman -Scc
# pacman -Syyu

но не помогло.
Затем прошел по ссылке
Из ответа, который помог тамошним вопрошающим

Okay. Can you try running:

sudo rm -r /etc/pacman.d/gnupg
sudo pacman -Sy gnupg archlinux-keyring manjaro-keyring
sudo pacman-key —init
sudo pacman-key —populate archlinux manjaro
sudo pacman-key —refresh-keys
sudo pacman -Sc
Try updating after that. If that does not work, the package might actually be corrupt.

я выбрал только команду

# pacman-key --refresh-keys 

и затем снова выполнил

# pacman -Su

и это сработало. Ошибок не получал.

Кстати, не по теме, но пользуясь случаем… В Arch при загрузке появляется какой-то drop-down terminal или это фишка Manjaro?

Aivar

#
5 лет, 3 месяца назад

Темы:

4

Сообщения:

6897

Участник с: 17 февраля 2011

Удивляете. Арч будет таким, каким вы его сделаете. Кто знает, может у манджары guake в автозагрузке…

Ссылки по теме

  • Создание пакетов
  • Откат пакетов
  • pacman (Русский)/Подпись пакетов
  • pacman (Русский)/Pacnew и Pacsave
  • pacman (Русский)/Восстановление локальной базы данных
  • pacman/Rosetta
  • pacman (Русский)/Советы и приёмы
  • ЧаВо#Управление пакетами
  • Обслуживание системы
  • Система сборки Arch
  • Официальные репозитории
  • Пользовательский репозиторий Arch

Состояние перевода: На этой странице представлен перевод статьи pacman. Дата последней синхронизации: 2 февраля 2020. Вы можете помочь синхронизировать перевод, если в английской версии произошли изменения.

[Система управления пакетами](https://en.wikipedia.org/wiki/ru:%D0%A1%D0%B8%D1%81%D1%82%D0%B5%D0%BC%D0%B0_%D1%83%D0%BF%D1%80%D0%B0%D0%B2%D0%BB%D0%B5%D0%BD%D0%B8%D1%8F_%D0%BF%D0%B0%D0%BA%D0%B5%D1%82%D0%B0%D0%BC%D0%B8 и пакеты в двоичном формате. Цель pacman — организация удобного управления пакетами вне зависимости от того, взяты они из официальных репозиториев или же собраны самостоятельно.

pacman поддерживает систему в актуальном состоянии, синхронизируя пакеты с сервером. Эта клиент-серверная модель позволяет пользователю скачивать/устанавливать пакеты со всеми требуемыми зависимостями всего одной командой.

pacman написан на языке Си и использует формат пакетов .pkg.tar.xz.

Совет: Официальный пакет pacman также содержит такие утилиты, как makepkg и vercmp(8). В пакет pacman-contrib вошли другие полезные программы, например, pactree и checkupdates, которые раньше были частью pacman. Команда pacman -Ql pacman pacman-contrib | grep -E 'bin/.+' выведет полный список доступных утилит.

Contents

  • 1 Использование
    • 1.1 Установка пакетов
      • 1.1.1 Установка отдельных пакетов
      • 1.1.2 Установка группы пакетов
    • 1.2 Удаление пакетов
    • 1.3 Обновление пакетов
    • 1.4 Запросы к базам данных пакетов
      • 1.4.1 Pactree
      • 1.4.2 Структура базы данных
    • 1.5 Очистка кэша пакетов
    • 1.6 Дополнительные команды
    • 1.7 Причина установки
    • 1.8 Поиск пакета по названию файла
  • 2 Настройка
    • 2.1 Глобальные параметры
      • 2.1.1 Сравнение версий пакетов перед обновлением
      • 2.1.2 Запрет на обновление отдельных пакетов
      • 2.1.3 Запрет на обновление группы пакетов
      • 2.1.4 Запрет на обновление файлов
      • 2.1.5 Запрет на установку файлов
      • 2.1.6 Работа с несколькими файлами настроек
      • 2.1.7 Хуки
    • 2.2 Репозитории и зеркала
      • 2.2.1 Безопасность пакетов
  • 3 Решение проблем
    • 3.1 Failed to commit transaction (conflicting files)
    • 3.2 Failed to commit transaction (invalid or corrupted package)
    • 3.3 Failed to init transaction (unable to lock database)
    • 3.4 Не удаётся найти пакет для установки
    • 3.5 Pacman падает при обновлении
    • 3.6 Переустановка pacman вручную
    • 3.7 Ошибка «Unable to find root device» после перезагрузки
    • 3.8 Signature from «User email@example.org» is unknown trust, installation failed
    • 3.9 Требование импортировать ключи PGP
    • 3.10 Error: key «0123456789ABCDEF» could not be looked up remotely
    • 3.11 Signature from «User email@archlinux.org» is invalid, installation failed
    • 3.12 Warning: current locale is invalid; using default «C» locale
    • 3.13 Pacman игнорирует настройки прокси
    • 3.14 Как переустановить все пакеты, сохранив информацию о том, какие из них установлены вручную, а какие — в качестве зависимостей?
    • 3.15 Cannot open shared object file
    • 3.16 Проблемы с загрузкой пакетов
    • 3.17 Failed retrieving file ‘core.db’ from mirror
  • 4 Пояснения
    • 4.1 Процесс установки/обновления/удаления пакета
  • 5 Смотрите также

Использование

В этом разделе приведена небольшая подборка доступных возможностей pacman. Больше примеров можно найти в руководстве pacman(8).

Совет: Если раньше вы использовали другой дистрибутив Linux, то будет полезно ознакомиться со статьёй Pacman Rosetta.

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

Примечание:

  • Часто у пакетов есть опциональные зависимости, которые не являются обязательными, но предоставляют дополнительную функциональность. Во время установки pacman выведет список опциональных зависимостей, но в файле pacman.log упоминаний о них не будет. Чтобы получить информацию об опциональных зависимостях пакета, используйте #Запросы к базам данных пакетов.
  • При установке пакета, который нужен только в качестве зависимости для другого пакета, в том числе опциональной, и который не будет использоваться напрямую, рекомендуется использовать параметр --asdeps. Подробнее смотрите раздел #Причина установки.

Важно: При установке пакетов старайтесь не синхронизировать базу данных пакетов без последующего обновления системы (например, на случай, если пакета уже нет в официальных репозиториях). В частности, не используйте команду pacman -Sy *название_пакета* вместо pacman -Sy**u** *название_пакета*, потому что это может привести к проблемам с зависимостями. Подробнее смотрите статью System maintenance#Частичные обновления не поддерживаются и ветку форума BBS#89328.

Установка отдельных пакетов

Для установки одного пакета или списка пакетов (включая зависимости) используйте следующую команду:

# pacman -S *название_пакета1* *название_пакета2* ...

Для установки списка пакетов при помощи поиска по регулярному выражению (смотрите эту ветку форума) выполните:

# pacman -S $(pacman -Ssq *регулярное_выражение*)

Если пакет имеет несколько версий в разных репозиториях (например, в extra и testing), можно указать, откуда именно следует установить пакет:

# pacman -S extra/*имя_пакета*

Чтобы установить несколько пакетов с частично совпадающими названиями, используйте фигурные скобки:

# pacman -S plasma-{desktop,mediacenter,nm}

Можно использовать несколько уровней вложенных фигурных скобок:

# pacman -S plasma-{workspace{,-wallpapers},pa}

Установка группы пакетов

Некоторые пакеты объединены в группы и могут устанавливаться одной командой. Например, после команды

вам будет предложено выбрать пакеты из группы gnome, которые вы хотели бы установить.

Некоторые группы содержат большое количество пакетов, и среди них могут быть всего несколько нужных или ненужных вам. Вместо того, чтобы вводить все необходимые вам номера, иногда удобнее выбрать или исключить отдельные числа или диапазоны чисел при помощи приведенного ниже синтаксиса:

Enter a selection (default=all): 1-10 15

— будут выбраны все пакеты в диапазоне с 1 по 10, а также 15;

Enter a selection (default=all): ^5-8 ^2

— будут выбраны все пакеты, кроме входящих в диапазон с 5 по 8, а также 2.

Чтобы увидеть список пакетов, принадлежащих к группе gnome, выполните:

Перечень групп можно найти на странице https://www.archlinux.org/groups/.

Примечание: Установлены будут все пакеты из списка, в том числе и те, которые уже были установлены в систему ранее — даже если они последней версии и не нуждаются в обновлении. Чтобы не устанавливать такие пакеты заново, укажите параметр --needed.

Удаление пакетов

Удалить пакет, не удаляя его зависимости:

# pacman -R *название_пакета*

Удалить пакет и те его зависимости, которые не нужны никаким другим пакетам:

# pacman -Rs *название_пакета*

Удалить пакет, его зависимости, а также все пакеты, для которых он сам является зависимостью:

Важно: Эта операция рекурсивна. Используйте её с осторожностью — есть риск удалить нужные пакеты.

# pacman -Rsc *название_пакета*

Удалить пакет, который требуется другому пакету, без удаления зависимостей:

Важно: Этой операции следует избегать, так как она может нанести тяжелый вред системе. Подробнее смотрите статью System maintenance#Избегайте определенных команд pacman.

# pacman -Rdd *название_пакета*

pacman создает резервные копии конфигурационных файлов удаляемых приложений и добавляет к ним расширение .pacsave. Если вы хотите удалить и эти файлы, используйте ключ -n:

# pacman -Rn *название_пакета*

Примечание: pacman не удаляет файлы настроек, которые созданы самими приложениями — например, скрытые файлы (имя которых начинается с точки) в домашнем каталоге).

Обновление пакетов

Важно:

  • Обновление системы следует выполнять регулярно, следуя рекомендациям в статье System maintenance#Обновление системы. При этом пользователь должен понимать смысл выполняемых действий, а не слепо повторять предложенные команды.
  • Arch поддерживает только полные обновления системы. Смотрите статьи System maintenance#Частичные обновления не поддерживаются и #Установка пакетов.

pacman полностью обновляет систему всего одной командой. Если система давно не обновлялась, процесс может занять довольно длительное время. Приведённая ниже команда одновременно синхронизирует базы данных репозиториев и выполняет обновление системы — при этом пакеты, которых нет в подключённых репозиториях, обновлены не будут:

Запросы к базам данных пакетов

Для взаимодействия с базами данных в pacman предусмотрены флаги -Q (база данных пакетов), -S (база данных синхронизации) и -F (база данных файлов). Команды pacman -Q --help, pacman -S --help и pacman -F --help выведут список возможных опций для этих флагов.

pacman может выполнять поиск в базе данных как среди названий пакетов, так и по их описаниям:

$ pacman -Ss *условие1* *условие2* ...

Иногда поиск с параметром -s выдаёт много ненужных результатов, поэтому имеет смысл ограничить поиск только названиями пакетов, отключив поиск по описаниям и другим полям. Для этого можно использовать регулярные выражения:

Искать среди установленных пакетов:

$ pacman -Qs *условие1* *условие2* ...

Искать пакет в репозиториях по названию файла:

$ pacman -F *условие1* *условие2* ...

Показать подробную информацию о пакете в репозитории:

$ pacman -Si *название_пакета*

То же самое — для установленного пакета:

$ pacman -Qi *название_пакета*

Если указать сразу два флага -i, то будет также выведен список резервных копий файлов и их состояние (модифицирован/нет):

$ pacman -Qii *название_пакета*

Вывести список файлов установленного пакета:

$ pacman -Ql *название_пакета*

Вывести список файлов пакета в репозитории:

$ pacman -Fl *название_пакета*

Проверить наличие файлов установленного пакета:

$ pacman -Qk *название_пакета*

С двумя флагами -k проверка будет более тщательной.

Узнать, какому пакету принадлежит файл:

$ pacman -Qo */путь/к/файлу/имя_файла*

Узнать, какому пакету в репозиториях принадлежит файл:

$ pacman -F */путь/к/файлу/имя_файла*

Вывести список пакетов, которые больше не требуются как зависимости («пакеты-сироты»):

Совет: Последнюю команду имеет смысл сделать пост-транзакционным хуком pacman, чтобы получить уведомление, если какое-то действие привело к появлению пакета-сироты. Это может быть полезно, например, если пакет был удалён из репозитория, вследствие чего на локальной системе он будет считаться сиротой (кроме случая, когда пакет был установлен явно). Чтобы не получать ошибку «failed to execute command» в случае отсутствия пакетов-сирот, укажите следующую команду в параметре Exec в описании хука: /usr/bin/bash -c "/usr/bin/pacman -Qtd || /usr/bin/echo '=> None found.'"

Вывести список пакетов, установленных явно (explicitly) и не являющихся зависимостями для других пакетов:

Другие полезные команды можно найти в статье pacman/Советы и приёмы.

Pactree

Примечание: pactree(8) больше не является частью пакета pacman. Теперь он входит в состав pacman-contrib.

Дерево зависимостей пакета можно узнать командой

$ pactree *название_пакета*

Чтобы увидеть «обратное» дерево зависимостей, т.е. список пакетов, которые сами зависят от указанного, используйте флаг pactree -r или утилиту whoneeds из пакета pkgtools.

Структура базы данных

Базы данных pacman обычно размещаются в каталоге /var/lib/pacman/sync. Для каждого подключённого в файле /etc/pacman.conf репозитория в этом каталоге находится соответствующий файл базы данных. Сам файл представляет собой gzip-сжатый tar-архив (с расширением .db), содержащий по одному каталогу для каждого пакета. Например, для пакета which содержимое каталога имеет вид:

$ tree which-2.21-5

В файле desc хранятся мета-данные пакета — описание, список зависимостей, размер, хэш-сумма MD5 и т.д.

Очистка кэша пакетов

Скачиваемые пакеты pacman сохраняет в каталог (/var/cache/pacman/pkg/). Устаревшие версии пакетов, как и версии пакетов удалённых, автоматически не удаляются. Такой подход обладает следующими преимуществами:

  1. Можно выполнить откат пакета без необходимости искать где-то (например, в архиве Arch Linux) его старую версию;
  2. Удалённый по ошибке пакет можно заново установить из кэша, не скачивая из репозитория.

Тем не менее, это означает, что время от времени необходимо чистить этот каталог самостоятельно, чтобы предотвратить его разрастание.

Скрипт paccache(8) из пакета pacman-contrib удаляет из кэша старые версии пакетов, как установленных в системе, так и уже удалённых, по умолчанию оставляя только 3 самые свежие:

Включите и запустите paccache.timer, чтобы очистка кэша выполнялась каждую неделю автоматически.

Совет: Также можно создать хук, чтобы очистка запускалась после каждого действия pacman. Подробнее смотрите примеры на форуме и пакет pacman-cleanup-hook.

При необходимости можно задать количество последних версий, которые нужно оставить. Команда для удаления всех версий, кроме последней:

# paccache --remove --keep 1

Флаг -u/--uninstalled позволяет ограничить действие paccache только версиями пакетов, которых в системе уже нет. Например, команда удаления всех кэшированных версий удалённых пакетов:

# paccache --remove --uninstalled --keep 0

Список возможных опций выводится командой paccache --help.

В pacman есть встроеный функционал очистки кэша и удаления баз данных репозиториев, которые были заблокированы в файле /etc/pacman.conf. Однако pacman гораздо менее гибок по сравнению с paccache и не даёт возможности сохранить некоторое количество последних версий, просто очищая каталог кэша.

Чтобы удалить все кэшированные версии удалённых пакетов и неиспользуемые базы данных, выполните:

Чтобы удалить вообще все файлы из кэша, укажите флаг очистки дважды:

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

pkgcacheclean и pacleaner — две альтернативные программы для очистки кэша.

Дополнительные команды

Скачать пакет без установки:

# pacman -Sw *название_пакета*

Установить пакет не из удалённого репозитория, а хранящийся локально (например, предварительно скачанный из AUR):

# pacman -U */путь/к/пакету/имя_пакета-версия.pkg.tar.xz*

Сохранить копию локально устанавливаемого пакета в кэше pacman:

# pacman -U file:*///путь/к/пакету/имя_пакета-версия.pkg.tar.xz*

Скачать и установить пакет из удаленного источника (но и не из репозиториев, перечисленных в конфигурационном файле pacman):

# pacman -U http:*//www.example.com/repo/example.pkg.tar.xz*

Флаг -p можно использовать для подавления стандартных действий -S, -U и -R.

Pacman всегда выводит список пакетов, которые будут установлены или удалены, и спрашивает разрешение пользователя перед выполнением действия.

Причина установки

Для pacman с точки зрения причины установки пакеты делятся на две категории:

  • установлен вручную (explicitly-installed): установлен пользователем командами pacman -S или pacman -U;
  • зависимость (dependency): установлен автоматически в процессе установки другого пакета, поскольку являлся его зависимостью.

При установке пакета можно принудительно изменить причину установки на зависимость:

# pacman -S --asdeps *название_пакета*

Совет: При установке опциональных зависимостей вручную стоит всегда указывать флаг --asdeps. Тогда при удалении пакетов-сирот ненужные опциональные зависимости тоже будут удаляться.

При переустановке пакета текущая причина установки не меняется.

Список установленных вручную пакетов выводится командой pacman -Qe, а пакетов-зависимостей — командой pacman -Qd.

Чтобы изменить причину установки уже установленного пакета, выполните:

# pacman -D --asdeps *название_пакета*

Для противоположной операции воспользуйтесь флагом --asexplicit.

Примечание: Не стоить использовать опции --asdeps и --asexplicit в команде обновления системы, например pacman -Syu *название_пакета* --asdeps. Это изменит причину установки не только для устанавливаемого пакета, но и для всех обновляемых.

Поиск пакета по названию файла

Синхронизировать базу данных файлов:

Найти пакет, содержащий определённый файл (например, файл pacman):

$ pacman -Fs pacman
core/pacman 5.0.1-4
    usr/bin/pacman
    usr/share/bash-completion/completions/pacman
extra/xscreensaver 5.36-1
    usr/lib/xscreensaver/pacman

Совет: Вы можете назначить задачу в Cron или таймер systemd для регулярной синхронизации баз данных.

Утилита pkgfile также осуществляет поиск пакетов по файлам, опираясь на свою базу данных; она обладает расширенной функциональностью по сравнению с pacman -F.

Настройка

Настройки pacman находятся в файле /etc/pacman.conf. Подробную информацию о файле настроек можно найти в руководстве pacman.conf(5).

Глобальные параметры

Глобальные настройки pacman указываются в разделе [options]. Помимо руководства pacman.conf(5) некоторая информация о настройках из этого раздела содержится в комментариях самого файла pacman.conf.

Сравнение версий пакетов перед обновлением

Чтобы увидеть сравнение старых и новых версий доступных для обновления пакетов, раскомментируйте строку VerbosePkgLists в файле pacman.conf. Теперь команда pacman -Syu будет выводить примерно следующее:

Package (6)             Old Version  New Version  Net Change  Download Size

extra/libmariadbclient  10.1.9-4     10.1.10-1      0.03 MiB       4.35 MiB
extra/libpng            1.6.19-1     1.6.20-1       0.00 MiB       0.23 MiB
extra/mariadb           10.1.9-4     10.1.10-1      0.26 MiB      13.80 MiB

Запрет на обновление отдельных пакетов

Важно: Будьте осторожны при использовании этой настройки, потому что частичные обновления не поддерживаются.

Чтобы пропустить пакет во время обновления системы добавьте его название в параметр IgnorePkg:

Если необходимо пропустить обновление для нескольких пакетов, укажите названия, разделив их пробелами, или используйте несколько строк IgnorePkg. Также можно использовать шаблоны поиска. Если нужно пропустить обновление пакета всего один раз, то лучше использовать опцию командной строки --ignore — здесь в качестве разделителя для названий пакетов используется запятая.

При необходимости обновить пакет из списка исключений всё же можно, командой pacman -S *название_пакета*: pacman при этом выведет напоминание, что пакет указан в IgnorePkg.

Запрет на обновление группы пакетов

Важно: Будьте осторожны при использовании этой настройки, потому что частичные обновления не поддерживаются.

Аналогично запрету на обновление отдельного пакета, можно запретить обновление сразу для целой группы, например:

Запрет на обновление файлов

Файлы, указанные в параметре NoUpgrade, не будут изменяться в процессе установки/обновления; новые версии этих файлов будут сохраняться с расширением .pacnew.

Примечание: Путь к файлу соответствует названию файла в tar-архиве пакета. Следовательно, указывать ведущий слэш не нужно.

Запрет на установку файлов

Чтобы запретить установку файлов в определённые каталоги, перечислите их в параметре NoExtract. Например, запрет установки юнитов systemd:

NoExtract=usr/lib/systemd/system/*

Совет: Pacman выводит предупреждение о недостающих файлах локализаций при обновлении пакетов, локали которых были удалены утилитами вроде localepurge или bleachbit. Чтобы отключить эти сообщения, закомментируйте параметр CheckSpace в файле pacman.conf, но имейте в виду, что это отключит функционал проверки наличия свободного места для всех пакетов.

Работа с несколькими файлами настроек

Если имеется несколько конфигурационных файлов (например, основная конфигурация и дополнительная с подключённым репозиторием testing), то работу с ними можно упростить, если вынести общие пункты настроек в отдельный файл и подключать его с помощью опции Include:

Include = */путь/к/файлу/общих/настроек*

В этом примере общие настройки вынесены в файл */путь/к/файлу/общих/настроек*. Приведённую выше строку нужно добавить в оба файла настроек, основной и дополнительный.

Хуки

Системные пре- и пост-транзакционные хуки хранятся в каталоге /usr/share/libalpm/hooks; pacman может выполнять хуки как из системного каталога, так и из каталогов, подключённых опцией — HookDir в файле pacman.conf (каталог по умолчанию — /etc/pacman.d/hooks). Название файла хука должно заканчиваться на .hook. Хуки pacman неинтерактивны.

В частности, хуки pacman используются в связке с systemd-sysusers и systemd-tmpfiles для автоматического создания пользователей и файлов в процессе установки пакетов. Например, пакет tomcat8 требует наличия пользователя tomcat8 и определённых каталогов, ему принадлежащих. Хуки systemd-sysusers.hook и systemd-tmpfiles.hook вызывают команды systemd-sysusers и systemd-tmpfiles соответственно, когда pacman видит в пакете указания на пользователей и временные файлы.

Хуки alpm подробно описаны в руководстве alpm-hooks(5).

Репозитории и зеркала

Помимо общего раздела [options] в файле pacman.conf также содержатся отдельные разделы для каждого из репозиториев. Репозиторий — набор пакетов, который физически находится на одном или нескольких серверах; эти сервера называются зеркалами репозитория.

Репозитории делятся на официальные и неофициальные. Порядок репозиториев в файле настроек имеет значение: если в разных репозиториях содержатся пакеты с одинаковым названием, то вне зависимости от их версий предпочтение отдаётся тому пакету, репозиторий которого ближе к началу файла. Чтобы подключённый репозиторий можно было использовать, сначала необходимо выполнить полное обновление системы.

Разделы репозиториев в файле pacman.conf содержат информацию о зеркалах. Список зеркал хранится в отдельном файле и подключается параметром Include. Например, зеркала официальных репозиториев подключаются из файла /etc/pacman.d/mirrorlist. Настройка зеркал описана в статье Mirrors.

Безопасность пакетов

Pacman использует цифровые подписи в качестве дополнительного механизма обеспечения безопасности пакетов. Настройки проверки подписей задаются параметром SigLevel. По умолчанию в разделе [options] задано глобальное значение SigLevel = Required DatabaseOptional, что означает проверку подписей всех пакетов без исключения. Можно задать особые правила проверки подписей для отдельных репозиториев, указав параметр SigLevel в соответствующих разделах. Подробнее см. pacman/Package signing.

Решение проблем

Failed to commit transaction (conflicting files)

Следующее сообщение об ошибке [1]:

error: could not prepare transaction
error: failed to commit transaction (conflicting files)
*пакет*: */путь/к/файлу* exists in filesystem
Errors occurred, no packages were upgraded.

означает, что при выполнении операции были обнаружены конфликтующие файлы. Pacman не будет их перезаписывать автоматически. Это не ошибка, так сделано специально.

Проблема решается тривиально. Сначала проверьте, не принадлежит ли файл другому пакету (pacman -Qo */путь/к/файлу*). Если принадлежит, создайте отчет об ошибке. Если проблемный файл не нужен другим пакетам, переименуйте его и перезапустите команду обновления. Если в дальнейшем проблем не возникнет, то старый файл можно удалить.

Если программа была установлена вручную без pacman — например, при помощи команды make install — необходимо удалить программу и все её файлы, а затем выполнить установку при помощи pacman. Смотрите также статью Поиск файлов, не принадлежащих ни одному пакету.

Информация о каждом установленном файле хранится в файле с метаданными пакета /var/lib/pacman/local/*пакет-версия*/files. При повреждении этого файла (он может быть пустым или отсутствовать) во время обновления пакета будет получена ошибка file exists in filesystem («файл существует в файловой системе»). Обычно такие ошибки возникают во время установки или обновления всего лишь одного пакета. Вместо ручного переименования или удаления конфликтующих файлов, принадлежащих данному пакету, лучше выполнить команду pacman -S --overwrite *шаблон* *пакет*, чтобы pacman принудительно перезаписал файлы, название которых совпадает с шаблоном.

Важно: Будьте осторожны при использовании ключа --overwrite. См. System maintenance#Избегайте определенных команд pacman

Failed to commit transaction (invalid or corrupted package)

Удалите все файлы .part (частично скачанные пакеты) из кэша pacman /var/cache/pacman/pkg. Причиной ошибки чаще всего является пользовательская команда в параметре XferCommand файла pacman.conf.

# find /var/cache/pacman/pkg/ -iname "*.part" -exec rm {} ;

Failed to init transaction (unable to lock database)

Когда pacman собирается внести изменения в базу данных пакетов, например, при установке пакета, он создает файл блокировки /var/lib/pacman/db.lck. Благодаря этому другой экземпляр pacman не сможет работать в то же самое время, что позволяет избежать повреждения базы.

Если работа pacman была прервана во время внесения изменений в базу, этот файл блокировки может остаться не удаленным. Если вы уверены, что на вашей машине не запущено других экземпляров pacman, удалите этот файл блокировки:

# rm /var/lib/pacman/db.lck

Не удаётся найти пакет для установки

Эта ошибка проявляется в сообщениях Not found in sync db, Target not found или Failed retrieving file.

Удостоверьтесь, что пакет, который вы пытаетесь установить, действительно существует. Если это так, возможно, список хранящихся в репозиториях пакетов устарел. Выполните pacman -Syu, чтобы получить новый список и обновить систему. Также убедитесь, что выбранные зеркала в рабочем состоянии, а репозитории настроены правильно.

Также есть вероятность того, что в вашей системе не включен репозиторий, содержащий нужный пакет — например, пакет находится в репозитории multilib, но multilib не включен в файле pacman.conf.

См. также FAQ#Почему в репозиториях есть только одна версия каждой библиотеки?

Pacman падает при обновлении

Если при удалении пакетов pacman завершает свою работу с ошибкой «database write» («запись в базу данных»), и после этого все попытки переустановки или обновления пакетов завершаются неудачей, сделайте следующее:

  1. Загрузитесь, используя Arch Live USB. Желательно, чтобы версия pacman в образе была не старше той, что установлена в системе.
  2. Смонтируйте корневую файловую систему, например, командой mount /dev/sdaX /mnt от root, и убедитесь, что в точке монтирования достаточно свободного места (команда df -h).
  3. Смонтируйте файловые системы proc, sys и dev: mount -t proc proc /mnt/proc; mount --rbind /sys /mnt/sys; mount --rbind /dev /mnt/dev
  4. Если в системе используются стандартное расположение баз данных и каталогов, то можно синхронизировать базу данных pacman и обновить систему командой pacman --sysroot /mnt -Syu от root.
  5. После обновления стоит убедиться, что в системе не осталось необновлённых нерабочих пакетов: find /mnt/usr/lib -size 0.
  6. Если такие пакеты всё же есть, их нужно переустановить: pacman --sysroot /mnt -S *package*.

Переустановка pacman вручную

Важно: Есть большая вероятность, что следуя рекомендациям ниже вы добьёте свою систему. Используйте их как последнее средство, если советы из раздела #Pacman падает при обновлении не помогли или нереализуемы.

Даже если pacman не подаёт признаков жизни, всё ещё можно починить его вручную, загрузив последние версии пакетов и распаковав файлы в нужные места. Последовательность действий:

  1. Узнайте зависимости пакета pacman.
  2. Скачайте пакеты с любого рабочего зеркала.
  3. Извлеките каждый пакет в корневой каталог.
  4. Переустановите эти пакеты командами pacman -S --overwrite *название_пакета*, чтобы обновить базу данных.
  5. Выполните полное обновление системы.

Если у вас имеется доступ к другой работоспособной системе с Arch Linux, полный список зависимостей можно узнать командой

$ pacman -Q $(pactree -u pacman)

Возможно, вам необходимо обновить только несколько пакетов, в зависимости от серьёзности проблемы. Пример команды распаковки архива пакета:

# tar -xvpwf *пакет.tar.xz* -C / --exclude .PKGINFO --exclude .INSTALL --exclude .MTREE --exclude .BUILDINFO

Обратите внимание на флаг -w, который включает интерактивный режим. Запускать распаковку неинтерактивно рискованно, потому что можно перезаписать важный файл. Также не забудьте, что пакеты нужно распаковывать в правильном порядке (сначала зависимости). На форуме рассмотрен пример процесса восстановления работоспособности pacman c несколькими неработающими пакетами-зависимостями.

Ошибка «Unable to find root device» после перезагрузки

Вероятно, при обновлении ядра был повреждён образ initramfs (например, при использовании pacman с опцией --overwrite). Для восстановления работоспособности есть два варианта, и первый из них — использовать fallback-образ.

Совет: Если вы удалили этот образ по каким-либо причинам, вы можете нажать клавишу Tab (при использовании Syslinux) или e (при использовании GRUB или systemd-boot), когда на экране появится меню загрузчика, переименовать образ в initramfs-linux-fallback.img и нажать Enter или b (в зависимости от используемого загрузчика), чтобы выполнить загрузку с новыми параметрами.

Когда система запустится, выполните команду пересборки образа initramfs либо из консоли, либо из терминала (для стандартного ядра linux):

Если этот способ не сработает, загрузитесь с Live-USB, смонтируйте корневой и загрузочный разделы, после чего сделайте chroot командой arch-chroot:

# arch-chroot /mnt
# pacman -Syu mkinitcpio systemd linux

Примечание:

  • Если у вас нет текущего релиза, или есть только какой-либо другой «live»-дистрибутив Linux, вы можете выполнить chroot, используя старый способ. Очевидно, при этом вам придется напечатать больше, чем просто arch-chroot для запуска соответствующего скрипта.
  • Если pacman выдает ошибку Could not resolve host, пожалуйста, проверьте ваше интернет-соединение.
  • Если вы не можете войти в окружение arch-chroot или chroot, но нуждаетесь в переустановке пакетов, можете использовать команду pacman --sysroot /mnt -Syu foo bar, чтобы указать pacman ваш корневой раздел.

Переустановка ядра (пакета linux) автоматически пересоздаст образ initramfs при помощи mkinitcpio -p linux. Нет необходимости дополнительно вводить эту команду.

После всего этого рекомендуется выполнить exit, umount /mnt/{boot,} и reboot.

Signature from «User email@example.org» is unknown trust, installation failed

Возможные решения:

  • Обновите существующие ключи командой pacman-key --refresh-keys.
  • Вручную обновите пакет archlinux-keyring командой pacman -Sy archlinux-keyring && pacman -Su.
  • Выполните полный сброс ключей.

Требование импортировать ключи PGP

При установке Arch Linux со старого ISO-образа скорее всего вы получите сообщение о необходимости выполнить импорт PGP-ключей — подтвердите загрузку. Если добавить ключи всё же не получится, синхронизируйте связку ключей или обновите пакет archlinux-keyring (см. выше).

Error: key «0123456789ABCDEF» could not be looked up remotely

Если пакеты подписаны свежими ключами, которые были добавлены к archlinux-keyring совсем недавно, это ключи могут оказаться недоступны в процессе обновления системы (проблема курицы и яйца). Установленный пакет archlinux-keyring должен обновиться, чтобы получить новые ключи. Pacman попытается обойти эту проблему обращением к серверу ключей, но это может оказаться невыполнимо из-за работы прокси или межсетевого экрана и приведёт к ошибке. Обновите пакет archlinux-keyring как описано выше.

Signature from «User email@archlinux.org» is invalid, installation failed

Такая ошибка может появиться, если системное время установлено неверно и подписи ключей кажутся устаревшими:

error: *пакет*: signature from "User <email@archlinux.org>" is invalid
error: failed to commit transaction (invalid or corrupted package (PGP signature))
Errors occured, no packages were upgraded.

Задайте правильное время (например, командой # ntpd -qg) и выполните # hwclock -w, после чего установите нужные пакеты или обновите систему.

Warning: current locale is invalid; using default «C» locale

Как сказано в сообщении ошибки, локаль системы настроена неправильно (см. Locale).

Pacman игнорирует настройки прокси

Удостоверьтесь, что соответствующие переменные окружения ($http_proxy, $ftp_proxy и т.д.) заданы верно. Если вы используете pacman вместе с sudo, необходимо настроить sudo на передачу переменных окружения в pacman. Также убедитесь, что настройки dirmngr в файле /etc/pacman.d/gnupg/dirmngr.conf содержат параметр honor-http-proxy, отвечающий за использование прокси при обновлении ключей.

Как переустановить все пакеты, сохранив информацию о том, какие из них установлены вручную, а какие — в качестве зависимостей?

Чтобы переустановить все пакеты из официальных репозиториев, выполните pacman -S $(pacman -Qnq) (опция -S сохраняет причину установки по умолчанию).

После этого необходимо переустановить все пакеты из неизвестных источников, список которых можно получить командой pacman -Qmq.

Cannot open shared object file

Скорее всего, это означает, что при выполнении предыдущей операции pacman удалил или повредил разделяемые библиотеки, необходимые для него самого.

Чтобы выйти из этой ситуации, нужно вручную распаковать необходимые библиотеки в вашу файловую систему. Сперва определите, в каком пакете содержится требуемая библиотека, а затем найдите этот пакет в кэше pacman (/var/cache/pacman/pkg/). Распакуйте разделяемую библиотеку в файловую систему. Это позволит вам запустить pacman.

Теперь необходимо переустановить испорченный пакет. При этом обязательно используйте ключ --overwrite, поскольку вы лишь распаковали системные файлы, но pacman об этом не знает. pacman корректно заменит ваш файл разделяемой библиотеки на тот, что имеется в пакете.

Вот и все. Обновите оставшуюся часть системы.

Проблемы с загрузкой пакетов

Были сообщения о некоторых сетевых проблемах, которые приводят к невозможности обновления/синхронизации: [2], [3]. При обычной установке Arch Linux эти проблемы не появляются, так как стандартный загрузчик файлов при этом заменяется другим (см. pacman/Tips and tricks#Performance). При установке Arch Linux в VirtualBox эта проблема также появляется, когда вы используете опцию виртуальной машины Host interface вместо NAT.

Failed retrieving file ‘core.db’ from mirror

Если зеркала настроены правильно, но вы получаете такое сообщение об ошибке, попробуйте выбрать другой сервер имён.

Пояснения

Процесс установки/обновления/удаления пакета

При выполнении операций с пакетами посредством pacman происходит следующее:

  1. pacman получает список пакетов для установки.
  2. pacman выполняет различные проверки на предмет возможности установки пакетов в систему.
  3. Если возможно применить какие-то из существующих пре-транзакционных хуков pacman, то они выполняются.
  4. Пакеты по очереди устанавливаются/обновляются/удаляются.
    1. Если у пакета есть скрипт установки, выполняется функция pre_install (или pre_upgrade/pre_remove в случае обновления или удаления пакета).
    2. pacman удаляет из системы все файлы старой версии пакета (в случае его обновления или удаления). Файлы настроек не удаляются (см. Pacman/Pacnew and Pacsave).
    3. pacman извлекает файлы из архива пакета и размещает их в системе (при установке или обновлении). Файлы, которые остались с прошлой установки, перезаписываются/модифицируются, а новые файлы настроек сохраняются рядом со старыми (см. предыдущий шаг) с добавлением к названию суффикса .pacnew.
    4. Если у пакета есть скрипт установки, выполняется функция post_install (post_upgrade или post_remove при обновлении/удалении).
  5. Если возможно применить какие-то из существующих пост-транзакционных хуков pacman, то они выполняются.

Смотрите также

  • Страница проекта Pacman
  • libalpm(3)
  • pacman(8)
  • pacman.conf(5)
  • repo-add(8)

Понравилась статья? Поделить с друзьями:
  • Error failed to build gem native extension ruby
  • Error failed to build gem native extension error failed to build gem native extension
  • Error failed to apply push options failed to open tun tap interface
  • Error failed to add operation for get api v1 connections
  • Error failed sending 1072 bytes