Проверить диск ext4 на ошибки

February 4th, 2011

Без категории, by Anakin_Sk.

Не так давно мы создавали загрузочную флешку, на случай, если нам понадобиться вдруг восстановить систему после непредвиденной ошибки. На этот раз ситуация такая – из за ошибки файловой системы ОС перестала запускаться, совсем, т.е. запустить в режиме безопасности вы ее не можете. Корень – это раздел ЖД с ФС ext4. Выход из такой ситуации – использовать системную утилиту для работы с ФС fsck.

Все, что нам нужно сделать, это запустить проверку нужного раздела ЖД. Выглядеть это должно примерно следующим образом – fsck.ext4 -p /dev/sda1, где ключ -p обязывает исправлять все ошибки автоматически, а /dev/sda1 это нужный нам раздел. Самый простой способ узнать адрес нужного раздела, запустить из меню Administation программу для работы с разделами ЖД – GPartEd.

Menu_016

Далее находим нужный нам раздел, и видим, что корень диска находится в /dev/sda7 (Смотрите точку монтирования, она д.б. /)

-dev-sda_-_gparted_017

Далее запускаем терминал и используем команду:

sudo fsck.ext4 -p /dev/sda7

Selection_019

Да кстати, учтите, что нужный раздел не должен быть примонтирован. Если программа говорит что filesytem is clean, то используйте ключ -f (force). Если все пройдет ОК, система начнет загружаться.

P.S. Так же выбранный метод можно использовать для периодической проверке, когда есть время, например /home раздела, ибо при попытке запуска fsck из основной системы вас ждет фейл с отмонтированием раздела.

Back Top

Tags: ext4, gparted, Ubuntu, загрузочная флешка

The fsck (stands for File System Consistency Check) is used to check and repair one or more Linux filesystems.

This check will run automatically at boot time when a filesystem inconsistencies detected. Also, can be run manually as needed.

You can use the fsck command to repair corrupted file systems when the system fails to boot, or a partition can’t be mounted, or if it’s become read-only.

In this article, we’ll see how to use the ‘fsck’ or ‘e2fsck’ command in Linux to repair a corrupted file system.

Note:

  • Execute the fsck on an unmounted file systems to avoid any data corruption in the file system.
  • For larger file systems, fsck may take a long time to run depending on system speed and disk sizes.

When the file system check is complete, fsck returns one of the following exit code:

Exit Code Description
0 No errors
1 Filesystem errors corrected
2 System should be rebooted
4 Filesystem errors left uncorrected
8 Operational error
16 Usage or syntax error
32 Checking canceled by user request
128 Shared-library error

Common Syntax:

fsck [option] [device or partition or mount point]

Corrupting EXT4 File System

We are going to intentionally corrupt the EXT4 file system by executing the below command. It trash’s randomly selected file system metadata blocks.

Make a Note: Please don’t test this on Production server, as this may damage your data badly.

sudo umount /data

Corrupting the ext4 file system.

sudo dd if=/dev/zero of=/dev/sdb1 bs=10000 skip=0 count=1

1+0 records in
1+0 records out
10000 bytes (10 kB, 9.8 KiB) copied, 0.00394663 s, 2.5 MB/s

When you try to load the file system, you will see the following error message because it was corrupted.

sudo mount /data

mount: /data: wrong fs type, bad option, bad superblock on /dev/sdb1, missing codepage or helper program, or other error.
Repairing EXT4 Filesystem in Linux

Repair Corrupted EXT4 & EXT3 File System

You can repair a non-root corrupted ext3 or ext4 file system on a running Linux system. fsck works as a wrapper for the fsck.ext3 and fsck.ext4 commands.

Make a note: If you are not able to unmount some of the Non-root volume due to an issue, boot the system into single user mode or rescue mode to repair it.

Step-1: Unmount the device that you want to run fsck.

sudo umount /dev/sdb1

Step-2: Run fsck to repair the file system:

sudo fsck.ext4 -p /dev/sdb1
  • -p : Automatically repair any issues that can be safely fixed without user intervention.

If the above option doesn’t resolve the issue, run the fsck command in the below format.

sudo fsck.ext4 -fvy /dev/sdb1

e2fsck 1.45.6 (20-Mar-2020)
ext2fs_open2: Bad magic number in super-block
fsck.ext4: Superblock invalid, trying backup blocks...
Resize inode not valid.  Recreate? yes

Pass 1: Checking inodes, blocks, and sizes
Pass 2: Checking directory structure
Pass 3: Checking directory connectivity
Pass 4: Checking reference counts
Pass 5: Checking group summary information
Block bitmap differences:  -65536 -65538 -(65541--65542) -(65546--65547) -(65549--65550) -(65555--65557)
.
.
Fix? yes

Free inodes count wrong for group #0 (8181, counted=8165).
Fix? yes

Free inodes count wrong (327669, counted=327653).
Fix? yes

Padding at end of inode bitmap is not set. Fix? yes


/dev/sdb1: ***** FILE SYSTEM WAS MODIFIED *****

          27 inodes used (0.01%, out of 327680)
           0 non-contiguous files (0.0%)
           0 non-contiguous directories (0.0%)
             # of inodes with ind/dind/tind blocks: 0/0/0
             Extent depth histogram: 19
       43294 blocks used (3.30%, out of 1310464)
           0 bad blocks
           0 large files

          16 regular files
           2 directories
           0 character device files
           0 block device files
           0 fifos
           0 links
           0 symbolic links (0 fast symbolic links)
           0 sockets
------------
          18 files

Step-3: Once the file system is repaired, mount the partition.

sudo mount /dev/sdb1

2) Repairing LVM Volume with fsck

fsck can be run on LVM logical volumes just like filesystems on standard partitions. Follow the below procedure for repairing a LVM partition:

You can also restore/recover the lvm volume instead of repairing it as needed.

Step-1: Make sure the specific LVM volume is in active state to run fsck. To check the status of LVM, run:

sudo lvscan

  inactive          '/dev/myvg/vol01' [1.00 GiB] inherit
  ACTIVE            '/dev/rhel/swap' [2.07 GiB] inherit
  ACTIVE            '/dev/rhel/root' [<26.93 GiB] inherit

If it’s 'inactive', activate it by running the following command.

sudo lvchange -ay /dev/myvg/vol01 -v

  Activating logical volume myvg/vol01.
  activation/volume_list configuration setting not defined: Checking only host tags for myvg/vol01.
  Creating myvg-vol01
  Loading table for myvg-vol01 (253:2).
  Resuming myvg-vol01 (253:2).

Step-2: Unmount the device or filesystem that you want to run fsck.

sudo umount /dev/myvg/vol01

Step-3: Run fsck to repair the file system. You must enter the path of the LVM volume to run fsck and not an actual physical partition.

sudo fsck.ext4 -fvy /dev/myvg/vol01

e2fsck 1.45.6 (20-Mar-2020)
/dev/myvg/vol01: clean, 24/65536 files, 14094/262144 blocks
  • -f : Force checking even if the file system seems clean.
  • -y : Assume an answer of `yes’ to all questions; allows e2fsck to be used non-interactively.
  • -v : Verbose mode

Step-4: Once the file system is repaired, mount the partition.

sudo mount /apps

Conclusion

In this tutorial, we’ve shown you how to repair a corrupted EXT4 filesystems on Linux. You can use the same procedure for EXT3 and other filesystems.

Also, shown you how to run e2fsck on the LVM volumes.

If you have any questions or feedback, feel free to comment below.

Программа fsck (расшифровывается как File System Consistency Check) используется для проверки и восстановления одной или нескольких файловых систем Linux.

Эта проверка запускается автоматически во время загрузки при обнаружении несоответствий в файловой системе.

Также, при необходимости, она может быть запущена вручную.

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

В этой статье мы рассмотрим, как использовать команду ‘fsck’ или ‘e2fsck’ в Linux для восстановления поврежденной файловой системы.

🗂️ Что такое Ext2, Ext3 и Ext4 и как создавать и конвертировать файловые системы Linux

Содержание

  1. Примечание:
  2. Повреждение файловой системы EXT4
  3. Восстановление поврежденной файловой системы EXT4 и EXT3
  4. 2) Восстановление тома LVM с помощью fsck
  5. Заключение

Примечание:

Выполняйте fsck на немонтированной файловой системе, чтобы избежать повреждения данных в ФС.

Для больших файловых систем выполнение fsck может занять много времени в зависимости от скорости системы и размера диска.

Когда проверка файловой системы завершена, fsck возвращает один из следующих кодов завершения:

КОД ЗАВЕРШЕНИЯ ОПИСАНИЕ
0 Нет ошибок
1 Исправлены ошибки файловой системы
2 Система должна быть перезагружена
4 Ошибки файловой системы, оставленные без исправления
8 Операционная ошибка
16 Ошибка использования или синтаксиса
32 Проверка отменяется по запросу пользователя
128 Ошибка в общей библиотеке

Общий синтаксис:

fsck [option] [device or partition or mount point]

Повреждение файловой системы EXT4

Мы намеренно повредим файловую систему EXT4, выполнив приведенную ниже команду.

Она удаляет случайно выбранные блоки метаданных файловой системы

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

sudo umount /data

Повреждение файловой системы ext4.

sudo dd if=/dev/zero of=/dev/sdb1 bs=10000 skip=0 count=1

1+0 records in
1+0 records out
10000 bytes (10 kB, 9.8 KiB) copied, 0.00394663 s, 2.5 MB/s

Когда вы попытаетесь загрузить файловую систему, вы увидите следующее сообщение об ошибке, поскольку она была повреждена.

sudo mount /data

mount: /data: wrong fs type, bad option, bad superblock on /dev/sdb1, missing codepage or helper program, or other error.

Восстановление поврежденной файловой системы EXT4 и EXT3

Вы можете восстановить поврежденную файловую систему ext3 или ext4 в работающей системе Linux. fsck работает как обертка для команд fsck.ext3 и fsck.ext4.

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

Шаг-1: Размонтируйте устройство, на котором вы хотите запустить fsck.

sudo umount /dev/sdb1

Шаг-2: Запустите fsck для восстановления файловой системы:

sudo fsck.ext4 -p /dev/sdb1

-p : Автоматически устранить все проблемы, которые могут быть безопасно устранены без вмешательства пользователя.

Если вышеуказанный вариант не устраняет проблему, выполните команду fsck в следующем формате.

sudo fsck.ext4 -fvy /dev/sdb1

e2fsck 1.45.6 (20-Mar-2020)
ext2fs_open2: Bad magic number in super-block
fsck.ext4: Superblock invalid, trying backup blocks...
Resize inode not valid.  Recreate? yes

Pass 1: Checking inodes, blocks, and sizes
Pass 2: Checking directory structure
Pass 3: Checking directory connectivity
Pass 4: Checking reference counts
Pass 5: Checking group summary information
Block bitmap differences:  -65536 -65538 -(65541--65542) -(65546--65547) -(65549--65550) -(65555--65557)
.
.
Fix? yes

Free inodes count wrong for group #0 (8181, counted=8165).
Fix? yes

Free inodes count wrong (327669, counted=327653).
Fix? yes

Padding at end of inode bitmap is not set. Fix? yes


/dev/sdb1: ***** FILE SYSTEM WAS MODIFIED *****

          27 inodes used (0.01%, out of 327680)
           0 non-contiguous files (0.0%)
           0 non-contiguous directories (0.0%)
             # of inodes with ind/dind/tind blocks: 0/0/0
             Extent depth histogram: 19
       43294 blocks used (3.30%, out of 1310464)
           0 bad blocks
           0 large files

          16 regular files
           2 directories
           0 character device files
           0 block device files
           0 fifos
           0 links
           0 symbolic links (0 fast symbolic links)
           0 sockets
------------
          18 files

Шаг-3: Как только файловая система будет восстановлена, смонтируйте раздел.

sudo mount /dev/sdb1

2) Восстановление тома LVM с помощью fsck

fsck можно запускать на логических томах LVM так же, как и на файловых системах стандартных разделов.

Для восстановления LVM-раздела следуйте приведенной ниже процедуре:

При необходимости вы также можете восстановить/восстановить том lvm вместо его ремонта.

Шаг-1: Убедитесь, что конкретный том LVM находится в активном состоянии для запуска fsck.

Чтобы проверить состояние LVM, выполните:

sudo lvscan

  inactive          '/dev/myvg/vol01' [1.00 GiB] inherit
  ACTIVE            '/dev/rhel/swap' [2.07 GiB] inherit
  ACTIVE            '/dev/rhel/root' [<26.93 GiB] inherit

Если он “inactive“, активируйте его, выполнив следующую команду.

sudo lvchange -ay /dev/myvg/vol01 -v

  Activating logical volume myvg/vol01.
  activation/volume_list configuration setting not defined: Checking only host tags for myvg/vol01.
  Creating myvg-vol01
  Loading table for myvg-vol01 (253:2).
  Resuming myvg-vol01 (253:2).

Шаг-2: Размонтируйте устройство или файловую систему, на которой вы хотите запустить fsck.

sudo umount /dev/myvg/vol01

Шаг-3: Запустите fsck для восстановления файловой системы.

Для запуска fsck необходимо ввести путь к LVM-тому, а не к реальному физическому разделу.

sudo fsck.ext4 -fvy /dev/myvg/vol01

e2fsck 1.45.6 (20-Mar-2020)
/dev/myvg/vol01: clean, 24/65536 files, 14094/262144 blocks
  • -f : Принудительная проверка, даже если файловая система кажется чистой.
  • -y : Предполагать ответ `yes’ на все вопросы; позволяет использовать e2fsck неинтерактивно.
  • -v : Подробный режим

Шаг-4: Как только файловая система будет восстановлена, смонтируйте раздел.

sudo mount /apps

Заключение

В этом руководстве мы показали вам, как восстановить поврежденную файловую систему EXT4 в Linux.

Вы можете использовать ту же процедуру для EXT3 и других файловых систем.

Также мы показали, как запустить e2fsck на томах LVM.

Если у вас есть вопросы или замечания, не стесняйтесь оставлять комментарии.

см. также:

  • 🐧 Как принудительно выполнить fsck при перезагрузке системы
  • #️⃣ Как добавить зашифрованный жесткий диск на Linux
  • 🛑 Команды Linux, которые вы никогда не должны запускать в своей системе
  • 🐧 Советы по обеспечению безопасности сервера CentOS – часть 1
  • 🐧 Проверка файловой системы Linux на наличие ошибок: команда FSCK с примерами
  • 🐧 Как зашифровать каталоги с помощью eCryptfs на Linux

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

fsck (file system check) — утилита для проверки и восстановления файловых систем Linux. Проверка файловых систем разных физических дисков выполняется параллельно, что позволяет значительно её ускорить (см. fsck(8)).

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

Проверка при загрузке

Механизм

Существует два возможных варианта:

  1. mkinitcpio предоставляет хук fsck для проверки корневой файловой системы перед монтированием. Корневой раздел должен быть смонтирован на запись и чтение (параметр ядра rw) [1].
  2. systemd проверяет все файловые системы, которым задано значение fsck больше 0 (либо параметром fstab, либо в пользовательском файле юнита). Корневая файловая система изначально должна быть смонтирована только на чтение (параметр ядра ro), и лишь позже перемонтирована на чтение-запись в fstab. Имейте в виду, что опция монтирования defaults подразумевает rw.

Рекомендуется по умолчанию использовать первый вариант. Если вы устанавливали систему в соответствии с руководством, то использоваться будет именно он. Если вы хотите вместо этого использовать вариант 2, то удалите хук fsck из mkinitcpio.conf и задайте параметр ядра ro. Кроме того, параметром ядра fsck.mode=skip можно полностью отключить fsck для обоих вариантов.

Принудительная проверка

Если вы используете base-хук mkinitcpio, то можно принудительно выполнять fsck во время загрузки, задав параметр ядра fsck.mode=force. Проверена будет каждая файловая система на машине.

В качестве альтернативы можно воспользоваться службой systemd systemd-fsck@.service(8), которая проверит все настроенные файловые системы, которые не были проверены в initramfs. Тем не менее, проверка корневой файловой системы этим способом может стать причиной задержки в время загрузки, поскольку файловая система будет перемонтироваться.

Примечание: Если вы используете другие дистрибутивы GNU/Linux, то учтите, что старые методы проверки вроде файлов forcefsck для каждой файловой системы или команды shutdown с флагом -F будут работать только с SysVinit и ранними версиями Upstart; работать с systemd они не будут. Решение, предложенное выше, является единственным рабочим для Arch Linux.

Советы и рекомандации

Восстановление повреждённых блоков

Следующая команда позволяет восстановить повреждённые участки файловых систем ext2/ext3/ext4 и FAT:

Важно: Разрешение на восстановление запрошено не будет. Подразумевается, что вы уже ответили «Да», запустив команду на выполнение.

# fsck -a

Интерактивное восстановление повреждённых блоков

Полезно в том случае, если файлы на загрузочном разделе были изменены, а журнал не обновился соответствующим образом. В этом случае размонтируйте загрузочный раздел и выполните:

# fsck -r диск

Изменение частоты проверки

Примечание: Команды tune2fs и dumpe2fs работают только с файловыми системами ext2/ext3/ext4.

По умолчанию fsck проверяет файловую систему каждые 30 загрузок (вычисляется отдельно для каждого раздела). Чтобы изменить частотку проверок, выполните:

# tune2fs -c 20 /dev/sda1

Здесь 20 — число загрузок между проверками. Если задать значение 1, то проверка будет выполняться при каждой загрузке, а значение 0 отключит сканирование.

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

# dumpe2fs -h /dev/sda1 | grep -i 'mount count'

Параметры fstab

fstab — файл системных настроек, который используется для передачи ядру Linux информации о том, какие разделы (файловые системы) монтировать и в какие точки дерева файловой системы.

Записи в /etc/fstab выглядят примерно следующим образом.

/dev/sda1   /         ext4      defaults       0  1
/dev/sda2   /other    ext4      defaults       0  2
/dev/sda3   /win      ntfs-3g   defaults       0  0

Шестое поле каждой строки (выделено) — опция fsck:

  • 0 — не проверять.
  • 1 — файловая система (раздел), которая должна быть проверена первой; для корневого раздела (/) должно использоваться именно это значение.
  • 2 — прочие файловые системы, которые должны быть проверены.

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

Не запускается fsck для отдельного раздела /usr

  1. Убедитесь, что используются соответствующие хуки в /etc/mkinitcpio.conf, а также что вы не забыли пересоздать initramfs после последнего редактирования этого файла.
  2. Проверьте fstab! Только корневому разделу должен быть задан параметр 1 в последнем поле, все остальные разделы должны иметь либо 2, либо 0. Также проверьте файл на наличие иных опечаток.

ext2fs: no external journal

Иногда (например, из-за внезапного отключения питания) файловые системы ext(3/4) могут повредиться так сильно, что восстановить их обычным способом не удастся. Как правило, при этом fsck выводит сообщение о том, что не удалось найти журнал (no external journal). В этом случае выполните команды ниже.

Отмонтируйте раздел от соответствующего каталога:

# umount каталог

Запишите на раздел новый журнал:

# tune2fs -j /dev/раздел

Запустите fsck, чтобы восстановить раздел:

# fsck -p /dev/раздел

Tag/tag.png

Duplicate Article
This article covers the same material as another article. More info…

See: SystemAdministration/Fsck and TestingStorageMedia

Introduction

Contents

  1. Introduction
  2. Basic filesystem checks and repairs

    1. e2fsprogs — ext2, ext3, ext4 filesystems
    2. dosfstools — FAT12, FAT16 and FAT32 (vfat) filesystem
    3. ntfs-3g (previously also ntfsprogs) — NTFS filesystem
    4. reiserfstools — reiserfs
    5. xfsprogs — xfs
  3. Missing superblock
  4. Bad blocks
  5. Sources and further reading

This guide will help diagnose filesystem problems one may come across on a GNU/Linux system. New sections are still being added to this howto.

Basic filesystem checks and repairs

The most common method of checking filesystem’s health is by running what’s commonly known as the fsck utility. This tool should only be run against an unmounted filesystem to check for possible issues. Nearly all well established filesystem types have their fsck tool. e.g.: ext2/3/4 filesystems have the e2fsck tool. Most notable exception until very recently was btrfs. There are also filesystems that do not need a filesystem check tool i.e.: read-only filesystems like iso9660 and udf.

e2fsprogs — ext2, ext3, ext4 filesystems

Ext2/3/4 have the previously mentioned e2fsck tool for checking and repairing filesystem. This is a part of e2fsprogs package — the package needs to be installed to have the fsck tool available. Unless one removes it in aptitude during installation, it should already be installed.

There are 4 ways the fsck tool usually gets run (listed in order of frequency of occurrence):

  1. it runs automatically during computer bootup every X days or Y mounts (whichever comes first). This is determined during the creation of the filesystem and can later be adjusted using tune2fs.
  2. it runs automatically if a filesystem has not been cleanly unmounted (e.g.: powercut)
  3. user runs it against an unmounted filesystem
  4. user makes it run at next bootup

case 1

When filesystem check is run automatically X days after the last check or after Y mounts, Ubuntu gives user the option to interrupt the check and continue bootup normally. It is recommended that user lets it finish the check.

case 2

If a filesystem has not been cleanly unmounted, the system detects a dirty bit on the filesystem during the next bootup and starts a check. It is strongly recommended that one lets it finish. It is almost certain there are errors on the filesystem that fsck will detect and attempt to fix. Nevertheless, one can still interrupt the check and let the system boot up on a possibly corrupted filesystem.

2 things can go wrong

  1. fsck dies — If fsck dies for whatever reason, you have the option to press ^D (Ctrl + D) to continue with an unchecked filesystem or run fsck manually. See e2fsck cheatsheet for details how.

  2. fsck fails to fix all errors with default settings — If fsck fails to fix all errors with default settings, it will ask to be run manually by the user. See e2fsck cheatsheet for details how.

case 3

User may run fsck against any filesystem that can be unmounted on a running system. e.g. if you can issue umount /dev/sda3 without an error, you can run fsck against /dev/sda3.

case 4

You can make your system run fsck by creating an empty ‘forcefsck’ file in the root of your root filesystem. i.e.: touch /forcefsck Filesystems that have 0 or nothing specified in the sixth column of your /etc/fstab, will not be checked

Till Ubuntu 6.06 you can also issue shutdown -rF now to reboot your filesystem and check all partitions with non-zero value in sixth column of your /etc/fstab. Later versions of Ubuntu use Upstart version of shutdown which does not support the -F option any more.

Refer to man fstab for what values are allowed.

e2fsck cheatsheet

e2fsck has softlinks in /sbin that one can use to keep the names of fsck tools more uniform. i.e. fsck.ext2, fsck.ext3 and fsck.ext4 (similarly, other filesystem types have e.g.: fsck.ntfs) This cheatsheet will make use of these softlinks and will use ext4 and /dev/sda1 as an example.

  • fsck.ext4 -p /dev/sda1 — will check filesystem on /dev/sda1 partition. It will also automatically fix all problems that can be fixed without human intervention. It will do nothing, if the partition is deemed clean (no dirty bit set).

  • fsck.ext4 -p -f /dev/sda1 — same as before, but fsck will ignore the fact that the filesystem is clean and check+fix it nevertheless.

  • fsck.ext4 -p -f -C0 /dev/sda1 — same as before, but with a progress bar.

  • fsck.ext4 -f -y /dev/sda1 — whereas previously fsck would ask for user input before fixing any nontrivial problems, -y means that it will simply assume you want to answer «YES» to all its suggestions, thus making the check completely non-interactive. This is potentially dangerous but sometimes unavoidable; especially when one has to go through thousands of errors. It is recommended that (if you can) you back up your partition before you have to run this kind of check. (see dd command for backing up filesystems/partitions/volumes)

  • fsck.ext4 -f -c -C0 /dev/sda1 — will attempt to find bad blocks on the device and make those blocks unusable by new files and directories.

  • fsck.ext4 -f -cc -C0 /dev/sda1 — a more thorough version of the bad blocks check.

  • fsck.ext4 -n -f -C0 /dev/sda1 — the -n option allows you to run fsck against a mounted filesystem in a read-only mode. This is almost completely pointless and will often result in false alarms. Do not use.

In order to create and check/repair these Microsoft(TM)’s filesystems, dosfstools package needs to be installed. Similarly to ext filesystems’ tools, dosfsck has softlinks too — fsck.msdos and fsck.vfat. Options, however, vary slightly.

dosfsck cheatsheet

These examples will use FAT32 and /dev/sdc1

  • fsck.vfat -n /dev/sdc1 — a simple non-interactive read-only check

  • fsck.vfat -a /dev/sdc1 — checks the file system and fixes non-interactively. Least destructive approach is always used.

  • fsck.vfat -r /dev/sdc1 — interactive repair. User is always prompted when there is more than a single approach to fixing a problem.

  • fsck.vfat -l -v -a -t /dev/sdc1 — a very verbose way of checking and repairing the filesystem non-interactively. The -t parameter will mark unreadable clusters as bad, thus making them unavailable to newly created files and directories.

Recovered data will be dumped in the root of the filesystem as fsck0000.rec, fsck0001.rec, etc. This is similar to CHK files created by scandisk and chkdisk on MS Windows.

ntfs-3g (previously also ntfsprogs) — NTFS filesystem

Due to the closed sourced nature of this filesystem and its complexity, there is no fsck.ntfs available on GNU/Linux (ntfsck isn’t being developed anymore). There is a simple tool called ntfsfix included in ntfs-3g package. Its focus isn’t on fixing NTFS volumes that have been seriously corrupted; its sole purpose seems to be making an NTFS volume mountable under GNU/Linux.

Normally, NTFS volumes are non-mountable if their dirty bit is set. ntfsfix can help with that by clearing trying to fix the most basic NTFS problems:

  • ntfsfix /dev/sda1 — will attempt to fix basic NTFS problems. e.g.: detects and fixes a Windows XP bug, leading to a corrupt MFT; clears bad cluster marks; fixes boot sector problems

  • ntfsfix -d /dev/sda1 — will clear the dirty bit on an NTFS volume.

  • ntfsfix -b /dev/sda1 — clears the list of bad sectors. This is useful after cloning an old disk with bad sectors to a new disk.

    Windows 8 and GNU/Linux cohabitation problems This segment is taken from http://www.tuxera.com/community/ntfs-3g-advanced/ When Windows 8 is restarted using its fast restarting feature, part of the metadata of all mounted partitions are restored to the state they were at the previous closing down. As a consequence, changes made on Linux may be lost. This can happen on any partition of an internal disk when leaving Windows 8 by selecting “Shut down” or “Hibernate”. Leaving Windows 8 by selecting “Restart” is apparently safe.

    To avoid any loss of data, be sure the fast restarting of Windows 8 is disabled. This can be achieved by issuing as an administrator the command : powercfg /h off

Install reiserfstools package to have reiserfsck and a softlink fsck.reiserfs available. Reiserfsck is a very talkative tool that will let you know what to do should it find errors.

  • fsck.reiserfs /dev/sda1 — a readonly check of the filesystem, no changes made (same as running with —check). This is what you should run before you include any other options.

  • fsck.reiserfs —fix-fixable /dev/sda1 — does basic fixes but will not rebuild filesystem tree

  • fsck.reiserfs —scan-whole-partition —rebuild-tree /dev/sda1 — if basic check recommends running with —rebuild-tree, run it with —scan-whole-partition and do NOT interrupt it! This will take a long time. On a non-empty 1TB partition, expect something in the range of 10-24 hours.

xfsprogs — xfs

If a check is necessary, it is performed automatically at mount time. Because of this, fsck.xfs is just a dummy shell script that does absolutely nothing. If you want to check the filesystem consistency and/or repair it, you can do so using the xfs_repair tool.

  • xfs_repair -n /dev/sda — will only scan the volume and report what fixes are needed. This is the no modify mode and you should run this first.

    • xfs_repair will exit with exit status 0 if it found no errors and with exit status 1 if it found some. (You can check exit status with echo $?)

  • xfs_repair /dev/sda — will scan the volume and perform all fixes necessary. Large volumes take long to process.

XFS filesystem has a feature called allocation groups (AG) that enable it to use more parallelism when allocating blocks and inodes. AGs are more or less self contained parts of the filesystem (separate free space and inode management). mkfs.xfs creates only a single AG by default.

xfs_repair checks and fixes your filesystems by going through 7 phases. Phase 3 (inode discovery and checks) and Phase 4 (extent discovery and checking) work sequentially through filesystem’s allocation groups (AG). With multiple AGs, this can be heavily parallelised. xfs_repair is clever enough to not process multiple AGs on same disks.

Do NOT bother with this if any of these is true for your system:

  • you created your XFS filesystem with only a single AG.
  • your xfs_repair is older than version 2.9.4 or you will make the checks even slower on GNU/Linux. You can check your version with xfs_repair -V

  • your filesystem does not span across multiple disks

otherwise:

  • xfs_repair -o ag_stride=8 -t 5 -v /dev/sda — same as previous example but reduces the check/fix time by utilising multiple threads, reports back on its progress every 5 minutes (default is 15) and its output is more verbose.

    • if your filesystem had 32 AGs, the -o ag_stride=8 would start 4 threads, one to process AGs 0-7, another for 8-15, etc… If ag_stride is not specified, it defaults to the number of AGs in the filesystem.

  • xfs_repair -o ag_stride=8 -t 5 -v -m 2048 /dev/sda — same as above but limits xfs_repair’s memory usage to a maximum of 2048 megabytes. By default, it would use up to 75% of available ram. Please note, -o bhash=xxx has been superseded by the -m option

== jfsutils — jfs == == btrfs ==

Missing superblock

Bad blocks

Sources and further reading

  • man pages
  • <XFS user guide> — more details about XFS filesystem

Понравилась статья? Поделить с друзьями:
  • Проверить джава код на ошибки
  • Проверить выборку на наличие грубых ошибок
  • Проверить вордовский файл на орфографические ошибки
  • Проверить внутреннюю память андроид на наличие ошибок
  • Проверить внешний диск на ошибки mac os