Linux single mode fsck

Использование утилиты fsck для исправления ошибок файловой системы в Linux

Оригинал: How to Use ‘fsck’ to Repair File System Errors in Linux
Автор: Marin Todorov
Дата публикации: 1 октября 2018 года
Перевод: А. Кривошей
Дата перевода: июль 2019 г.

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

Это можно выполнить с помощью системной утилиты fsck (file system consistency check). Эта проверка может быть выполнена автоматически во время загрузки или запущена вручную.

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

Когда нужно использовать fsck в Linux

Существуют разные сценарии, когда вам понадобится запустить fsck. Вот несколько примеров:

Система не загружается.
Файлы в системе поврежденны (часто вы можете увидеть ошибку ввода/вывода).
Подключенный диск (включая флэшки/SD-карты) не работает должным образом.

Опции fsck

Команда Fsck должна быть запущена с привилегиями суперпользователя (root). Вы можете использовать ее с разными аргументами. Их использование зависит от вашего конкретного случая. Ниже вы увидите некоторые из наиболее важных опций:

-A — используется для проверки всех файловых систем. Список берется из /etc/fstab.
-C — показывать индикатор выполнения.
-l — блокирует устройство, чтобы гарантировать, что никакая другая программа не попытается использовать раздел во время проверки.
-M — не проверять смонтированные файловые системы.
-N — только показывать, что будет сделано — не делать никаких реальных изменений.
-P — если вы хотите проверять файловые системы параллельно, включая корневую.
-R — не проверять корневую файловую систему. Это полезно только вместе с ‘-A‘.
-r — предоставить статистику для каждого проверяемого устройства.
-T — не показывает заголовок.
-t — исключительно указать типы файловых систем, которые будут проверяться. Типы могут быть разделены запятыми.
-V — предоставить описание того, что делается.

Как запустить fsck для исправления ошибок файловой системы Linux

Чтобы запустить fsck, вам нужно убедиться, что раздел, который вы собираетесь проверить, не смонтирован. Для этой статьи я буду использовать мой второй диск /dev/sdb, смонтированный в /mnt.

Вот что произойдет, если я попытаюсь запустить fsck на смонтированном разделе.

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

Теперь fsck можно запустить безопасно.

Понимание кодов выхода fsck

После запуска fsck она вернет код выхода. Эти коды можно увидеть в руководстве fsck, выполнив:

Исправление ошибок файловой системы Linux

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

Флаг -y автоматически даёт ответ «да» на любые запросы от fsck для исправления ошибок.

Точно так же вы можете запустить команду на всех файловых системах (без корневой):

Как запустить fsck в корневом разделе Linux

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

1. Принудительно использовать fsck при загрузке системы
2. Запустить fsck в режиме восстановления

Мы рассмотрим обе ситуации.

Принудительная проверка корневой файловой системы с помощью fsck при загрузке системы

Это относительно легко выполнить, единственное, что вам нужно сделать, это создать файл с именем forcefsck в корневом разделе вашей системы. Используйте следующую команду:

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

После загрузки системы проверьте, существует ли этот файл:

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

Запуск fsck в режиме восстановления

Запуск fsck в режиме восстановления требует еще нескольких шагов. Сначала подготовьте систему к перезагрузке. Остановите все важные службы, такие как MySQL/MariaDB и т. д., а затем перезагрузите компьютер.

Читайте также:  Что такое asus smart gesture для windows 10

Во время загрузки удерживайте нажатой клавишу Shift, чтобы отобразилось меню grub. Выберите «Advanced options».

Затем выберите «Recovery mode».

В следующем меню выберите «fsck».

Вас спросят, хотите ли вы перемонтировать вашу корневую файловую систему. Выберите «yes».

Вы должны увидеть что-то похожее на это.

Затем вы можете вернуться к нормальной загрузке, выбрав «Resume».

Заключение

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

Источник

Linux fsck command

On Unix-like operating systems, the fsck command checks and repairs a Linux file system.

This page describes the GNU/Linux version of fsck.

Description

fsck stands for :file system consistency check:. On most systems, fsck is run at boot time if certain conditions are detected. Usually, these conditions are:

  • A file system is marked as «dirty» — its written state is inconsistent with data that was scheduled to be written; or,
  • A file system was mounted a set number of times without being checked.

The fsck command itself interacts with a matching filesystem-specific fsck command created by the filesystem’s authors. Regardless of filesystem type, fsck generally has three modes of operation:

  • Check for errors, and prompt the user interactively to decide how to resolve individual problems;
  • Check for errors, and attempt to fix any errors automatically; or,
  • Check for errors, and make no attempt to repair them, but display the errors on standard output.

While normally run at boot time, fsck can run manually on unmounted filesystems by a superuser.

Technical description

fsck is used to check, and optionally repair, one or more filesystems.

filesys is a device name (e.g., /dev/hdc1, /dev/sdb2), a mount point (e.g., /, /usr, /home), or an ext2 label or UUID specifier (for example «UUID=8868abf6-88c5-4a83-98b8-bfc24057f7bd» or «LABEL=root«).

Normally, fsck tries to handle filesystems on different physical disk drives in parallel to reduce the total amount of time needed to check all of them.

If no filesystems are specified on the command line, and the -A option is not specified, fsck defaults to checking filesystems in /etc/fstab serially. This is equivalent to the combination of the -A and -s options.

The exit code returned by fsck is a unique number representing the sum of the following condition values:

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 — Fsck canceled by user request
128 — Shared-library error

The exit code returned when multiple filesystems are checked is the bitwise OR of the exit codes for each filesystem that is checked.

In actuality, fsck is a front-end for the various filesystem checkers (fsck.fstype) available under Linux. The filesystem-specific checker is searched for in /sbin first, then in /etc/fs and /etc, and finally in the directories listed in the PATH environment variable.

Read filesystem-specific checker manual pages for further details. For example, to learn more about ext3-specific fsck checking, run:

Syntax

Options

-l Lock the whole-disk device by an exclusive flock. This option can be used with one device only (this means that -A and -l are mutually exclusive). This option is recommended when more fsck instances are executed in the same time. The option is ignored when used for multiple devices or for non-rotating disks. fsck does not lock underlying devices when executed to check stacked devices (e.g., MD or DM); this feature is not implemented yet.
-s Serialize fsck operations. This is a good idea if you are checking multiple filesystems and the checkers are in an interactive mode. Note: e2fsck runs in an interactive mode by default. To make e2fsck run in a non-interactive mode, you must specify the -p or -a option, if you want for errors to be corrected automatically, or the -n option if you do not.
-t fslist Specifies the type(s) of filesystem to be checked. When the -A flag is specified, only filesystems that match fslist are checked. The fslist parameter is a comma-separated list of filesystems and options specifiers. All the filesystems in this comma-separated list may be prefixed by a negation operator ‘no‘ or ‘!‘, which requests that only those filesystems not listed in fslist are checked. If none of the filesystems in fslist are prefixed by a negation operator, then only those listed filesystems are checked.

Options specifiers may be included in the comma-separated fslist. They must have the format opts=fs-option. If an options specifier is present, then only filesystems which contain fs-option in their mount options field of /etc/fstab are checked. If the options specifier is prefixed by a negation operator, then only those filesystems that do not have fs-option in their mount options field of /etc/fstab are checked.

For example, if opts=ro appears in fslist, then only filesystems listed in /etc/fstab with the ro option are checked.

For compatibility with Mandrake distributions with boot scripts dependant on an unauthorized UI change to the fsck program, if a filesystem type of loop is found in fslist, it is treated as if opts=loop were specified as an argument to the -t option.

Normally, the filesystem type is deduced by searching for filesys in the /etc/fstab file and using the corresponding entry. If the type cannot be deduced, and there is only a single filesystem given as an argument to the -t option, fsck uses the specified filesystem type. If this type is not available, then the default filesystem type (currently ext2) is used. -A Walk through the /etc/fstab file and try to check all filesystems in one run. This option is often used from the /etc/rc system initialization file, instead of multiple commands for checking a single filesystem.

The root filesystem is checked first unless the -P option is specified (see below). After that, filesystems are checked in the order specified by the fs_passno (the sixth) field in the /etc/fstab file. Filesystems with a fs_passno value of 0 are skipped and are not checked at all. Filesystems with a fs_passno value of greater than zero are checked in order, with filesystems with the lowest fs_passno number being checked first. If there are multiple filesystems with the same pass number, fsck attempts to check them in parallel, although it avoids running multiple filesystem checks on the same physical disk.

fsck does not check stacked devices (RAIDs, dm-crypt, . ) in parallel with any other device. See below for FSCK_FORCE_ALL_PARALLEL setting. The /sys filesystem is used to determine dependencies between devices.

Hence, a very common configuration in /etc/fstab files is to set the root filesystem to have a fs_passno value of 1 and to set all other filesystems to have a fs_passno value of 2. This allows fsck to automatically run filesystem checkers in parallel if it’s advantageous to do so. System administrators might choose not to use this configuration if they need to avoid multiple filesystem checks running in parallel for some reason — for example, if the machine in question is short on memory so that excessive paging is a concern.

fsck normally does not check whether the device actually exists before calling a filesystem specific checker. Therefore, non-existing devices may cause the system to enter filesystem repair mode during boot if the filesystem specific checker returns a fatal error. The /etc/fstab mount option nofail may be used to have fsck skip non-existing devices. fsck also skips non-existing devices that have the special filesystem type auto. -C [fd] Display completion/progress bars for those filesystem checkers (currently only for ext2 and ext3) which support them. Fsck manages the filesystem checkers so that only one of them displays a progress bar at a time. GUI front-ends may specify a file descriptor fd, where the progress bar information is sent to that file descriptor. -M Do not check mounted filesystems and return an exit code of 0 for mounted filesystems. -N Don’t do anything; show what would be done. -P When the -A flag is set, check the root filesystem in parallel with the other filesystems. This is not the safest thing in the world to do; if the root filesystem is in doubt, things like the e2fsck executable might be corrupted! This option is mainly provided for those sysadmins who don’t want to repartition the root filesystem to be small and compact (which is really the right solution). -R When checking all filesystems with the -A flag, skip the root filesystem. This is useful in case the root filesystem is already mounted read-write. -T Don’t show the title on startup. -V Produce verbose output, including all filesystem-specific commands that are executed.

Filesystem-specific options

Options that are not understood by fsck are passed to the filesystem-specific checker. These arguments must not take arguments, as there is no way for fsck to be able to properly guess which options take arguments and which don’t.

Options and arguments which follow the are treated as filesystem-specific options to be passed to the filesystem-specific checker.

Please note that fsck is not designed to pass arbitrarily complicated options to filesystem-specific checkers. If you’re doing something complicated, execute the filesystem-specific checker directly. If you pass fsck some horribly complicated options and arguments, and it doesn’t do what you expect, you’re almost certainly doing something you shouldn’t be doing with fsck. Options to different filesystem-specific fsck‘s are not standardized. If in doubt, please consult the man pages of the filesystem-specific checker. Although not guaranteed, the following options are supported by most filesystem checkers:

-a Automatically repair the filesystem without any questions (use this option with caution). Note that e2fsck supports -a for backward compatibility only. This option is mapped to e2fsck‘s -p option that is safe to use, unlike the -a option that some filesystem checkers support.
-n For some filesystem-specific checkers, the -n option causes the fs-specific fsck to avoid attempting to repair any problems, but report such problems to stdout. However, this is not true for all filesystem-specific checkers. In particular, fsck.reiserfs does not report any corruption if given this option. fsck.minix does not support the -n option at all.
-r Interactively repair the filesystem (ask for confirmations). Note: It is generally a bad idea to use this option if multiple fsck‘s are being run in parallel. Also, note that this is e2fsck‘s default behavior; it supports this option for backward compatibility reasons only.
-y For some filesystem-specific checkers, the -y option causes the fs-specific fsck to always attempt to fix any detected filesystem corruption automatically. Sometimes an expert can do better driving the fsck manually. Note that not all filesystem-specific checkers implement this option. In particular, fsck.minix and fsck.cramfs do not support the -y option.

Examples

Do not run fsck on a mounted filesystem! If you run fsck on a filesystem that is currently mounted, (at best) you receive an error message, and (at worst) corrupt your filesystem data. If you’re going to check your filesystem with fsck, drop into single-user mode and make sure the filesystem is unmounted before you proceed.

Dropping into single-user mode

These instructions should help you bring your Linux system into single-user mode and unmount any filesystems you want to check with fsck.

First, initiate runlevel 1 (single-user mode) with the init command:

Now unmount the filesystem using umount. For instance, if /home is mounted on /dev/sda2, you could run:

Make sure to run umount for any filesystem you want to check with fsck.

Checking filesystems

This command attempts to check /dev/sda2, and report any errors it finds.

Check /dev/sda2, and attempt to automatically fix any errors found.

Check all configured filesystems. fsck processes the file /etc/fstab and check all file systems listed there. Systems are checked in order of their

value, as listed in the fstab file. Systems with a pass value of 0 are skipped; the system with a pass value of 1 is listed first, and remaining systems are checked in ascending order of their pass value.

View all configured filesystems. Output resembles the following:

View all filesystems that can be checked with fsck. Filesystems appear as extensions to the fsck.* files; for example:

Check /dev/sda2 for errors, but do not attempt to repair them; instead, print any errors to standard output.

Normally, fsck skips parts of the filesystem marked as «clean» — meaning all pending writes were successfully made. The -f («force») option specifies that fsck should check parts of the filesystem even if they are not «dirty». The result is a less efficient, but a more thorough check.

This command checks the ext2 filesystem on the floppy diskette device /dev/fd0.

mkfs — Build a Linux file system, usually a hard disk partition.

Источник

Читайте также:  Настройка network manager astra linux
Оцените статью