Every time I try to install or remove a package, I get this error. I thought maybe it was the hard disk, but a disk check gave me a clean bill of health.
dpkg: unrecoverable fatal error, aborting:
reading files list for package 'linux-headers-3.16.0-31': Input/output error
E: Sub-process /usr/bin/dpkg returned an error code (2)
A package failed to install. Trying to recover:
I tried the solution of removing the listing for this file from the dpkg status file, but to no avail. I tried purging the package but no use. I’m stuck at this point as nothing I can find on Google helps.
Update:
This is now what the error says:
dpkg: unrecoverable fatal error, aborting:
E: Sub-process /usr/bin/dpkg returned an error code (2)
A package failed to install. Trying to recover:
After trying: https://askubuntu.com/a/603305/1992
Update2:
Seems the drive has bad sectors, but the reallocated sector count is 0. The drive is relatively old, however, so I expect some issues. I won’t be able to replace it immediately, and until then I would still like to be able to keep the system up to date (especially for security reasons).
I noted that there was an issue with coping some md5 checksums related to the package mentioned in the error, but I don’t know what to do with those, such as if clearing them would allow dpkg to continue.
You’ve experienced (at least) a bad block on your disk. Unfortunately, it hit an XFS data structure, so you’ve lost some filesystem metadata. I hope you have backups.
Check smartctl
Hopefully you have smartctl installed (it needs to run as root, e.g., via sudo). If installed, it should give output like this:
ID# ATTRIBUTE_NAME FLAG VALUE WORST THRESH TYPE UPDATED WHEN_FAILED RAW_VALUE
1 Raw_Read_Error_Rate 0x000f 103 098 006 Pre-fail Always - 212688305
3 Spin_Up_Time 0x0003 094 094 000 Pre-fail Always - 0
4 Start_Stop_Count 0x0032 100 100 020 Old_age Always - 76
5 Reallocated_Sector_Ct 0x0033 002 002 036 Pre-fail Always FAILING_NOW 4015
7 Seek_Error_Rate 0x000f 084 060 030 Pre-fail Always - 291678490
9 Power_On_Hours 0x0032 052 052 000 Old_age Always - 42540
10 Spin_Retry_Count 0x0013 100 100 097 Pre-fail Always - 0
12 Power_Cycle_Count 0x0032 100 100 020 Old_age Always - 39
183 Runtime_Bad_Block 0x0032 098 098 000 Old_age Always - 2
184 End-to-End_Error 0x0032 100 100 099 Old_age Always - 0
187 Reported_Uncorrect 0x0032 018 018 000 Old_age Always - 82
188 Command_Timeout 0x0032 100 097 000 Old_age Always - 25770393781
189 High_Fly_Writes 0x003a 084 084 000 Old_age Always - 16
190 Airflow_Temperature_Cel 0x0022 061 061 045 Old_age Always - 39 (Min/Max 38/39)
194 Temperature_Celsius 0x0022 039 040 000 Old_age Always - 39 (0 16 0 0 0)
195 Hardware_ECC_Recovered 0x001a 034 013 000 Old_age Always - 212688305
197 Current_Pending_Sector 0x0012 100 099 000 Old_age Always - 0
198 Offline_Uncorrectable 0x0010 100 099 000 Old_age Offline - 0
199 UDMA_CRC_Error_Count 0x003e 200 200 000 Old_age Always - 0
240 Head_Flying_Hours 0x0000 100 253 000 Old_age Offline - 42617 (160 246 0)
241 Total_LBAs_Written 0x0000 100 253 000 Old_age Offline - 3791056483
242 Total_LBAs_Read 0x0000 100 253 000 Old_age Offline - 1003117143
The exact attributes shown vary from disk to disk, but most all of them have a 197 and/or 198 telling you how many un-repaired bad sectors the disk knows about. In the above output, you can see #5 is FAILING_NOW, and it’s type is Pre-fail. That means the disk firmware expects the disk to fail within 24 hours. If you have any failed attributes, especially pre-fail ones, I’d replace the disk (and if its still under warranty, you should be able to RMA it).
If you do not have smartctl
If you don’t have smartctl, now is not the time to install it.
Critical next step
If you have any important files on the machine disk—especially ones that haven’t already been backed up—attempt to copy them to a different disk, USB flash drive, network share, etc. Your filesystem has been damaged, and it’s possible this is your last chance to do so easily.
Use a live system to run smartctl, xfs_repair
If you don’t have smartctl installed, you can reboot (after copying off important data!) into a live system (from CD, USB stick, etc.) and run smartctl from there. You can also use xfs_repair from the live system to attempt filesystem repair. (Please read the manpage for xfs_repair first; I confess to not having much experience with XFS).
Note that disks made in the last decade or two have spare sectors and will use on of them to replace the bad sector the next time it’s written to. smartctl -A will normally have attributes showing how many times this has been done.
After filesystem repair
If there were important files you couldn’t grab before, you can now try again.
Depending on bad the damage was (how many files you lost, and which ones), you’ll need to either re-install a few packages (using dpkg -i or apt-get install --reinstall) or, if it was bad, re-install the OS.
Of course, if you have a recent full-system backup, probably easiest to restore from backup.
How to prevent this in the future
Using two disks (in a mdraid RAID1 mirror) allows the kernel to deal with bad blocks by reading the sector from the other disk. It then writes the correct data back, allowing the disk to use a spare sector. You can also run RAID1 between two partitions on the same disk, which will half your available space but protect against bad sectors (but not against the disk failing entirely).
Some filesystems (e.g., btrfs with «duplicate» mode) can keep two copies of their metadata or your data, also protecting against bad sectors.
I wanted to install bluefish editor but I got this error. This is not the first error I got involving packages. I installed Linux Mint 17 two days ago and every time after a reboot there is some kind of problem with packages. Anyone have an idea?
user@username ~ $ sudo apt-get install bluefish
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following extra packages will be installed:
bluefish-data bluefish-plugins
Suggested packages:
bluefish-dbg libxml2-utils tidy weblint-perl weblint
The following NEW packages will be installed:
bluefish bluefish-data bluefish-plugins
0 upgraded, 3 newly installed, 0 to remove and 0 not upgraded.
Need to get 0 B/2 548 kB of archives.
After this operation, 9 484 kB of additional disk space will be used.
Do you want to continue? [Y/n] Y
E: Sub-process /usr/bin/dpkg returned an error code (2)
additional info:
sudo apt-get upgrade
as well as
sudo apt-get -f install
run with no error
Edits:
sudo dpkg -C does nothing
user@username ~ $ df -h
Filesystem Size Used Avail Use% Mounted on
/dev/sda6 161G 14G 140G 9% /
none 4,0K 0 4,0K 0% /sys/fs/cgroup
udev 2,0G 4,0K 2,0G 1% /dev
tmpfs 396M 1,4M 394M 1% /run
none 5,0M 0 5,0M 0% /run/lock
none 2,0G 1,7M 2,0G 1% /run/shm
none 100M 20K 100M 1% /run/user
/dev/sda5 168G 67G 102G 40% /mnt/DATA
user@username ~ $ sudo apt-get -fv install bluefish
apt 1.0.1ubuntu2 for amd64 compiled on Oct 8 2014 12:36:19
Supported modules:
*Ver: Standard .deb
*Pkg: Debian dpkg interface (Priority 30)
Pkg: Debian APT solver interface (Priority -1000)
S.L: 'deb' Standard Debian binary tree
S.L: 'deb-src' Standard Debian source tree
Idx: Debian Source Index
Idx: Debian Package Index
Idx: Debian Translation Index
Idx: Debian dpkg status file
Idx: EDSP scenario file
0
1
При попытке установить gcc-8-base (https://packages.debian.org/sid/amd64/gcc-8-base) выдает ошибку :
dpkg-deb: ошибка: в архиве «gcc-8-base_8-20180321-1ubuntu1_amd64.deb» содержится преждевременный элемент «control.tar.xz», до «control.tar.gz», прекращаем
dpkg: ошибка при обработке архива gcc-8-base_8-20180321-1ubuntu1_amd64.deb (--install):
подпроцесс dpkg-deb --control возвратил код ошибки 2
При обработке следующих пакетов произошли ошибки:
gcc-8-base_8-20180321-1ubuntu1_amd64.deb
Хеш сверял, все совпадает.
Как быть?

У меня очень старенький винт, потихоньку сыплется. Поэтому часто бывают всякие «неожиданности». Но это не всё. Часто при обновлениях случается чт-то от вас не зависящее, и не всегда этому виной кривые руки. Бывает, что dpkg спотыкается обо что-либо, и дальше всё.. ничего обновить в системе, установить или удалить вы через aptitude (apt-get) вы не сможете… Как вариант, можно посмотреть список зависимостей, и удалять всё ручками, но я считаю что это не айс — удалять каждый файлик, править конфиги… Может это и true linux way, но увы, сейчас уже третье тысячелетие, и я отказался от такого извращения. Поэтому мы просто попытаемся починить dpkg.
Итак, приступим:
dpkg — это программное обеспечение, являющееся основой системы управления пакетами в Debian. dpkg используется для установки, удаления, и получения информации о .deb пакетах.
Подробнее смотрите в Wiki, я лишь опишу некоторые проблемы, встречающиеся при обработке пакетов.
1) Что поможет в 80% случаев:
Зачастую достаточно просто запросить из хранилища(репозитория) новый список пакетов:
sudo aptitude update
sudo aptitude install -f
И установить обновления:
sudo aptitude safe-upgrade
Бывает что проблема — это плохо сконфигурированный пакет. Поэтому мы просто её ещё раз переконфигурируем:
sudo dpkg --configure -a
2) Остальные «сложные» случаи:
Для остальных случаев придётся переконфигурировать всё:
sudo dpkg-reconfigure -a
Осторожно, может занять много времени 
Или именно этот пакет:
sudo dpkg-reconfigure --default-priority %pack_name%
Ну бывает что нужно переконфигурировать его, даже если он поломан или неисправен:
sudo dpkg-reconfigure --force %pack_name%
!ВНИМАНИЕ! Использовать осторожно!
Если и это не помогает, то смотрим что именно произошло, не боимся гуглить и так далее, например у меня было вот что:
3) Конкретные случаи:
1) Падение dpkg - /var/lib/dpkg/available: Input/output error.
E: Sub-process /usr/bin/dpkg returned an error code (2)
dpkg: при работе функции buffer_read(fd) произошла ошибка: копирование файла информации /var/lib/dpkg/available: Input/output error
Дааааа… Как всегда косяки, ну ничего, где-то мы такое видали. Минутный поиск по форуму сообщества и на глаза вылазит лекарство:
sudo dpkg --configure -a
либо
sudo apt-get install -f && sudo dpkg --configure -a
К сожалению никаких результатов в моем случае это не дало.
Ищем дальше. Гугл толком ничего не даёт, найдены пару вариантов с англоязычного форума линукс. К сожалению не помогает. Ну ладно значит будем думать головой…
Идём по адресу /var/lib/dpkg/ находим файл available, пытаемся открыть — filed. Осматриваемся в папке,и видим интересный файл под названием available_old.
Значит, при обновлении пакетов была сделана резервная копия этого файла со старым содержимым. Открываем, копируем содержимое , удаляем available и создаём на его месте новый файл с тем же названием. Вставляем содержимое из available_old.
Проверяем обновления
sudo apt-get update
есть. Запускаем
sudo apt-get upgrade
и о чудо, всё работает. Теперь можно и продолжать настройку системы. Также возможен другой вариант лечения dpkg.
sudo dpkg --clear-avail #удалить информацию о доступных пакетах.
далее
sudo apt-get update #обновление информации о пакетах.
но это при условии, что ваш файл не окажется битым, как в моём случае.
Да, чуть не забыл при внесении данного сообщения начал меня раздражать SCIM Method? он так и норовил подсунуть мне какой-нибудь арабско-еврейско-хрензнает какой шрифт. Пришлось избавится
apt-get remove scim
Взято с тыц’а
2) Удалил пакет руками — теперь aptitude ругается, что делать?
dpkg: не удалось обработать параметр %pack_name% (--configure):
подпроцесс post-installation script возвратил код ошибки 1
При обработке следующих пакетов произошли ошибки:
%pack_name%
E: Sub-process /usr/bin/dpkg returned an error code (1)
В таком случае можно удалить пакет через dpkg:
dpkg --purge %pack_name% #удалит всё что о нём было известно вместе с ним
3) в списке файлов пакета %pack_name% отсутствует завершающий символ новой строки
aptitude install -f
Чтение списков пакетов... Готово
Построение дерева зависимостей
Чтение информации о состоянии... Готово
Чтение информации о расширенных состояниях
Инициализация состояний пакетов... Готово
(Чтение базы данных ... dpkg: невосстановимая ошибка, прекращение работы:
в списке файлов пакета %pack_name% отсутствует завершающий символ новой строки
E: Sub-process /usr/bin/dpkg returned an error code (2)
Не удалось установить пакет. Попытка восстановить:
Чтение списков пакетов... Готово
Построение дерева зависимостей
Чтение информации о состоянии... Готово
Чтение информации о расширенных состояниях
Инициализация состояний пакетов... Готово
Я гуглил много, оказалось решение очень простое:
sudo kate /var/lib/dpkg/status
После чего Ctrl+F — вводим в поиск %pack_name% и удаляем всё что с ним связано, после чего делаем пункт 1) и вуаля, dpkg вернулся из мёртвых, Ressurect III lvl окрыляет!
ПОДРОБНАЯ ИНФОРМАЦИЯ о dpkg на русском можно глянуть тут: тыц
Если нада, можно сюда скопипастить, но не думаю что нужно…
Проапгрейдил, исправил бОльшинство орфографических ошибок, привёл всё к единому формату. Любые дополнения приветствуются. В данный момент ищутся любые другие ошибки в dpkg, которые решаются способами, которых тут ещё нет.
Ну и спасибо баламутику за баламутивание 
