Fsck проверка диска 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/раздел

FSCK – очень важная утилита для Linux / Unix, она используется для проверки и исправления ошибок в файловой системе.

Она похоже на утилиту «chkdsk» в операционных системах Windows.

Она также доступна для операционных систем Linux, MacOS, FreeBSD.

FSCK означает «File System Consistency Check», и в большинстве случаев он запускается во время загрузки, но может также запускаться суперпользователем вручную, если возникнет такая необходимость.

Может использоваться с 3 режимами работы,

1- Проверка наличия ошибок и позволить пользователю решить, что делать с каждой ошибкой,

2- Проверка на наличие ошибок и возможность сделать фикс автоматически, или,

3- Проверка наличия ошибок и возможность отобразить ошибку, но не выполнять фикс.

Содержание

  1. Синтаксис использования команды FSCK
  2. Команда Fsck с примерами
  3. Выполним проверку на ошибки в одном разделе
  4. Проверьте файловую систему на ошибки и исправьте их автоматически
  5. Проверьте файловую систему на наличие ошибок, но не исправляйте их
  6. Выполним проверку на ошибки на всех разделах
  7. Проверим раздел с указанной файловой системой
  8. Выполнять проверку только на несмонтированных дисках

Синтаксис использования команды FSCK

$ fsck options drives

Опции, которые можно использовать с командой fsck:

  • -p Автоматический фикс (без вопросов)
  • -n не вносить изменений в файловую систему
  • -у принять «yes» на все вопросы
  • -c Проверить наличие плохих блоков и добавить их в список.
  • -f Принудительная проверка, даже если файловая система помечена как чистая
  • -v подробный режим
  • -b использование альтернативного суперблока
  • -B blocksize Принудительный размер блоков при поиске суперблока
  • -j external_journal Установить местоположение внешнего журнала
  • -l bad_blocks_file Добавить в список плохих блоков
  • -L bad_blocks_file Установить список плохих блоков

Мы можем использовать любую из этих опций, в зависимости от операции, которую нам нужно выполнить.

Давайте обсудим некоторые варианты команды fsck с примерами.

Команда Fsck с примерами

Примечание: – Прежде чем обсуждать какие-либо примеры, прочтите это. Мы не должны использовать FSCK на смонтированных дисках, так как высока вероятность того, что fsck на смонтированном диске повредит диск навсегда.

Поэтому перед выполнением fsck мы должны отмонтировать диск с помощью следующей команды:

$ umount drivename

Например:

$ umount /dev/sdb1

Вы можете проверить номер раздела с помощью следующей команды:

$ fdisk -l

Также при запуске fsck мы можем получить некоторые коды ошибок.

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

  • 0 – нет ошибок
  • 1 – исправлены ошибки файловой системы
  • 2 – система должна быть перезагружена
  • 4 – Ошибки файловой системы оставлены без исправлений
  • 8 – Операционная ошибка
  • 16 – ошибка использования или синтаксиса
  • 32 – Fsck отменен по запросу пользователя
  • 128 – Ошибка общей библиотеки

Теперь давайте обсудим использование команды fsck с примерами в системах Linux.

Выполним проверку на ошибки в одном разделе

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

$ umount /dev/sdb1

$ fsck /dev/sdb1

Проверьте файловую систему на ошибки и исправьте их автоматически

Запустите команду fsck с параметром «a» для проверки целостности и автоматического восстановления, выполните следующую команду.

Мы также можем использовать опцию «у» вместо опции «а».

$ fsck -a /dev/sdb1

Проверьте файловую систему на наличие ошибок, но не исправляйте их

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

$ fsck -n /dev/sdb1

Выполним проверку на ошибки на всех разделах

Чтобы выполнить проверку файловой системы для всех разделов за один раз, используйте fsck с опцией «A»

$ fsck -A

Чтобы отключить проверку корневой файловой системы, мы будем использовать опцию «R»

$ fsck -AR

Проверим раздел с указанной файловой системой

Чтобы запустить fsck на всех разделах с указанным типом файловой системы, например, «ext4», используйте fsck с опцией «t», а затем тип файловой системы,

$ fsck -t ext4 /dev/sdb1

или

$ fsck -t -A ext4

Выполнять проверку только на несмонтированных дисках

Чтобы убедиться, что fsck выполняется только на несмонтированных дисках, мы будем использовать опцию «M» при запуске fsck,

$ fsck -AM

Вот наше короткое руководство по команде fsck с примерами.

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

Introduction

The fsck (File System Consistency Check) Linux utility checks filesystems for errors or outstanding issues. The tool is used to fix potential errors and generate reports.

This utility comes by default with Linux distributions. No specific steps or an installation procedure is required to use fsck. Once you load the terminal, you are ready to exploit the functionalities of the tool.

Follow this guide to learn how to use fsck to check and repair filesystem on a Linux machine. The tutorial will list examples of how to use the tool and for which use cases.

How to use fsck command to check and repair filesystem in Linux

Prerequisites

  • Linux or UNIX-like system
  • Access to a terminal or command line
  • A user with root permissions to run the tool

When to Use fsck in Linux

The fsck tool can be used in various situations:

  • Use fsck to run a filesystem check as preventive maintenance or when there is an issue with your system.
  • One common problem fsck can diagnose is when the system fails to boot.
  • Another one is when you get an input/output error when the files on your system become corrupt.
  • You can also use the fsck utility to check the health of external drives, such as SD cards or USB flash drives.

Basic fsck Syntax

The basic syntax for the fsck utility follows this pattern:

fsck <options> <filesystem>

In the above example, filesystem can be a device, a partition, a mount point, etc. You can also use filesystem-specific options at the end of the command.

There are a few steps to do before you check and repair your file system. You need to locate a device and unmount.

View Mounted Disks and Partitions

To view all mounted devices on your system and check disk location, use one of the available tools in Linux.

One method to locate the disk you want to scan is to list the filesystem disks with the df command:

df -h
Terminal output when running a df -h command

The tool prints the data usage on your system and filesystems. Take note of the disk you want to check with the fsck command.

To view partitions for your first disk, for example, use the following command:

sudo parted /dev/sda 'print'

sda is how Linux refers to your first SCSI disk. If you have two, the second would be sdb, and so on.

In our example, we got one result since there was only one partition on this virtual machine. You will get more results if you have more partitions.

The terminal output when listing Linux partitions.

The disk name here is /dev/sda and then the number of partitions is shown in the Number column. In our case, it is one: sda1.

Unmount the Disk

A warning when you try to unmount a mounted disk or partition.

Before you can run a disk check with fsck, you need to unmount a disk or partition. If you try to run fsck on a mounted disk or partition, you will get a warning:

Make sure to run the unmount command:

sudo umount /dev/sdb

Replace /dev/sdb with the device you want to unmount.

Note that you cannot unmount root filesystems. Hence, now fsck can’t be used on a running machine. More on that towards the end of the guide.

Run fsck to Check for Errors

Now that you unmounted the disk, you can run fsck. To check the second disk, enter:

sudo fsck /dev/sdb
The output after running a fsck command to check the second disk.

The above example shows the output for a clean disk. If there are multiple issues on your disk, a prompt appears for each one where you have to confirm the action.

The exit code the fsck utility returns is the sum of these states:

Possible exit codes for the fsck command.

Mount the Disk

When you finish checking and repairing a device, mount the disk so you can use it again.

In our case, we will remount the sdb disk:

mount /dev/sdb

Do a Dry Run with fsck

Before you perform a live check, you can do a test run with fsck. Pass the -N option to the fsck command to perform a test:

sudo fsck -N /dev/sdb

The output prints what would happen but does not perform any actions.

Fix Detected Errors Automatically with fsck

To try to fix potential problems without getting any prompts, pass the -y option to fsck.

sudo fsck -y /dev/sdb

This way, you say “yes, try to fix all detected errors” without being prompted every time.

If no errors are found, the output looks the same as without the -y option.

Skip Repair but Print fsck Errors in the Output

Use the -n option if you want to check potential error on a file system without repairing them.

We have a second drive sdb with some journaling errors. The -n flag prints the error without fixing it:

sudo fsck -n /dev/sdb
Use -n fsck option to print errors without fixing them.

Force fsck to Do a Filesystem Check

When you perform a fsck on a clean device, the tool skips the filesystem check. If you want to force the filesystem check, use the -f option.

For example:

sudo fsck -f /dev/sdb
Force the fsck tool to do a filesystem check

The scan will perform all five checks to search for corruptions even when it thinks there are no issues.

Run fsck on All Filesystems at Once

If you want to perform a check on all filesystems with fsck in one go, pass the -A flag. This option will go through the etc/fstab file in one run.

Since root filesystems can’t be unmounted on a running machine, add the -R option to skip them:

fsck -AR

To avoid the prompts, add the -y option we talked about.

Skip fsck on a Specific Filesystem

If you want fsck to skip checking a filesystem, you need to add -t and “no” before a filesystem.

For example, to skip ext3 filesystem, run this command:

sudo fsck -AR -t noext3 -y

We added -y to skip the prompts.

Skip Fsck on Mounted Filesystems

To make sure you do not try to run fsck on a mounted filesystem, add the -M option. This flag tells the fsck tool to skip any mounted filesystems.

To show you the difference, we will run fsck on sdb while it is mounted, and then when we unmount it.

sudo fsck -M /dev/sdb
The output of fsck tool to skip any mounted filesystems.

While sdb is mounted, the tool exits without running a check. Then, we unmount sdb and run the same command again. This time, fsck checks the disk and reports it as clean, or with errors.

Note: To remove the first title line of the fsck tool “fsck from util-linux 2.31.1” use the -T option.

Run fsck on Linux Root Partition

As we already mentioned, fsck cannot check root partitions on a running machine since they are mounted and in use. However, even Linux root partitions can be checked if you boot into recovery mode and run the fsck check:

1. To do so, power on or reboot your machine through the GUI or by using the terminal:

sudo reboot

2. Press and hold the shift key during boot-up. The GNU GRUB menu appears.

3. Select Advanced options for Ubuntu.

Linux recovery mode screen.

4. Then, select the entry with (recovery mode) at the end. Let the system load into the Recovery Menu.

5. Select fsck from the menu.

Linux recovery menu select fsck tool.

6. Confirm by selecting <Yes> at the prompt.

Recovery mode confirmation message when fsck is selected.

7. Once finished, select resume at the recovery menu to boot up the machine.

Resume option selected when the tool finishes checking a root partition.

What if fsck is Interrupted?

You should not interrupt the fsck tool while it is in progress. However, if the process is interrupted, fsck will finish the ongoing check and then stop.

In case the utility found an error while the check was in process, it will not try to fix anything if interrupted. You can rerun the check next time and let it finish.

fsck Linux Command Options Summary

To wrap up, below is the list of the options you can use with the fsck Linux utility.

Option Description
-a Try to repair filesystem errors automatically. There will be no prompts, so use it with caution. 
-A Check all filesystems listed in /etc/fstab.
-C Show progress for ext2 and ext3 filesystems. 
-f Force fsck to check a filesystem. The tool checks even when the filesystem appears to be clean.
-l Lock the device to prevent other programs from using the partition during the scan and repair. 
-M Do not check mounted filesystems. The tool returns an exit code 0 when a filesystem is mounted.
-N Do a dry run. The output prints what the fsck would do without executing any actions. The warning or error messages are printed as well.  
-P Use to run a scan on multiple filesystems in parallel. It can cause issues, depending on your setup. Use with caution. 
-R Tell the fsck tool not to check the root filesystems when you use the -A option. 
-r Print device statistics. 
-t Specify which filesystems type(s) to check with fsck. Consult the man page for detailed information. 
-T Hide the title when the tool starts. 
-y Try to repair filesystem errors automatically during the check. 
-V Verbose output. 

Note: Learn about the error code SIGSEGV (signal segmentation violation) and how to troubleshoot it.

Conclusion

Now you know how to use fsck Linux command to check and repair filesystems. The guide provided examples of the tool’s functionalities and features.

Make sure you have root permissions before running the listed commands. For a detailed description of all options, you can consult the man file of the tool or visit the fsck Linux man page.

Sometimes bad things happen to good systems.

Fortunately, you’re a Linux user and you have fsck (file system check) to help with a potentially corrupted filesystem. This utility is used for checking and (optionally) repairing the file system.

There are several scenarios where you may want to use fsck. Typically, you would want to run this command if your system will not boot, a device (external drives or storage media) is not functioning properly, or if you have seen evidence of file corruption.

Fsck is a actually a «front-end» for a number of file system specific checkers like fsck.vfat, fsck.ext2, etc. These do not need to be specified, but you may be able to find more advanced options in the man pages of these more precise commands.

Introduction to the fsck command

The fsck command follows a pattern similar to most Linux commands.

fsck [options] [filesystem]

If you do not specify a filesystem, the system will analyze your fstab file (/etc/fstab) for the devices to scan.

You will need to run the command either as root user or use it with sudo.

You can use fdisk or df command to list the hard drive in Linux. This way, you can specify which device to be checked with fsck command.

Disk /dev/nvme0n1: 238.49 GiB, 256060514304 bytes, 500118192 sectors
Disk model: THNSN5256GPUK NVMe TOSHIBA 256GB        
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: 014A45DC-22A2-4FC0-BEEA-25A6F2406380

Device            Start       End   Sectors   Size Type
/dev/nvme0n1p1     2048   1050623   1048576   512M EFI System
/dev/nvme0n1p2  1050624  98563270  97512647  46.5G Linux filesystem
/dev/nvme0n1p3 98564096 500117503 401553408 191.5G Linux filesystem

Unmount the device before running fsck

Do not run fsck on a mounted device, you will need to unmount the target first to avoid damage to your files.

If you try running fsck on a mounted device, you should see an error like this:

[email protected]:~$ sudo fsck /dev/sda3
fsck from util-linux 2.34
e2fsck 1.45.5 (07-Jan-2020)
/dev/sda3 is mounted.
e2fsck: Cannot continue, aborting.

Running fsck on a normal, healthy drive looks like this:

[email protected]:~$ sudo fsck /dev/sda2
fsck from util-linux 2.34
fsck.fat 4.1 (2017-01-24)
/dev/sda2: 5 files, 1967/1972 clusters

While fsck accepts a device name like /dev/sda, you may elect to enter the UUID to avoid confusion with mounting and unmounting devices. The UUID is a fixed value assigned to your device and will not be affected by these system changes.

Understanding exit codes for the fsck command

This is a list of the codes that may be returned from fsck after inspecting a disk. Your exit code will be a sum of these codes if you analyze one disk. If you are using fsck on multiple devices, it will return the bit-wise OR of the two sums.

  • 0 — No errors
  • 1 — File system errors corrected
  • 2 — System should be rebooted
  • 4 — File system errors left uncorrected
  • 8 — Operational error
  • 16 — Usage or syntax error
  • 32 — Fsck canceled by user request
  • 128 — Shared library error

You can check the exit code of the last run command using echo $? command.

Practical usage of the fsck command

Now that you are a tad bit familiar with the fsck command, let’s see practical use cases of this command.

Repair a USB disk and other removable devices

For our purpose, let’s assume that you have already identified the problematic device /dev/sdb.

First, you need to make sure that the drive has been unmounted:

sudo umount /dev/sdb

Now run the fsck command:

sudo fsck /dev/sdb

Check the output for any errors. If none displayed, check the exit code with echo $?.

There are also some option flags that we can add to allow some automated correction. These commands aren’t standardized though, and you should verify the filesystem type and compare documentation from that specific man page.

Despite that, generally you can use -p to allow fsck to automatically apply repairs.

sudo fsck -p /dev/sdb

Similarly, -y will apply corrections to any detected filesystem corruption.

Repair the root file system

You cannot unmount the root partition while the system is active. If you suspect your main file system is corrupted, you have to use a different approach here.

There are actually a few different options that you can use. You can run fsck at boot time, in rescue mode, or use a recovery-themed live cd.

Many Linux distributions will automatically force fsck at start up after a certain number of failed boot attempts. If you prefer to take matters into your own hands, you can schedule the system to do this ourselves.

Most modern Linux versions feature a tool called tune2fs.

sudo tune2fs -c 1 /dev/sda

Presuming your root device is dev/sda, this is the command you would enter.

Now, what’s actually happening is that you’re changing the system settings so that fsck is run every n number of boots (1 in the example). You could also set this to a standard time interval. The options are days, weeks, or months.

Let’s say that you want fsck to run any time that you boot if there hasn’t been a check in a week. You could use -i to specify the interval and the command would look like this.

sudo tune2fs -i 1w /dev/sda	

If you’re using systemd, you can force run fsck at your next boot by entering the following:

fsck.mode=force
fsck.repair=yes

Conclusion

You can always turn to the man-pages for more information. Just use man fsck in the terminal.

I hope you learned something new about the fsck command. If you have any comments or questions, please leave them below.

Linux Filesystems are responsible for organizing how data is stored and recovered. One way or another, with time, the filesystem may become corrupted and certain parts of it may not be accessible. If your filesystem develops such inconsistency it is recommended to verify its integrity.

This can be completed via a system utility called fsck (file system consistency check), which checks the root file system automatically during boot time or ran manually.

In this article, we are going to review the fsck command and its usage to help you repair Linux disk errors.

Table of Contents

1

When to Use fsck Command in Linux

There are different scenarios when you will want to run fsck. Here are a few examples:

  • The system fails to boot.
  • Files on the system become corrupt (often you may see input/output error).
  • The attached drive (including flash drives/SD cards) is not working as expected.

fsck Command Options

The fsck command needs to be run with superuser privileges or root. You can use it with different arguments. Their usage depends on your specific case. Below you will see some of the more important options:

  • -A – Used for checking all filesystems. The list is taken from /etc/fstab.
  • -C – Show progress bar.
  • -l – Locks the device to guarantee no other program will try to use the partition during the check.
  • -M – Do not check mounted filesystems.
  • -N – Only show what would be done – no actual changes are made.
  • -P – If you want to check filesystems in parallel, including root.
  • -R – Do not check the root filesystem. This is useful only with ‘-A‘.
  • -r – Provide statistics for each device that is being checked.
  • -T – Does not show the title.
  • -t – Exclusively specify the Linux filesystem types to be checked. Types can be comma-separated lists.
  • -V – Provide a description of what is being done.

Run fsck Command to Repair Linux File System Errors

In order to run fsck, you will need to ensure that the partition you are going to check is not mounted. For the purpose of this article, I will use my second drive /dev/sdb mounted in /mnt.

Here is what happens if I try to run fsck when the partition is mounted.

# fsck /dev/sdb

Run fsck on Mounted Partition

Run fsck on Mounted Partition

To avoid this unmount the partition using.

# umount /dev/sdb

Then fsck can be safely run with.

# fsck /dev/sdb

Run fsck on Linux Partition

Run fsck on Linux Partition

Understanding fsck Exit Codes

After running fsck, it will return an exit code. These codes can be seen in fsck’s manual by running:

# man fsck

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

Fsck Repair Linux Filesystem

Sometimes more than one error can be found on a filesystem. In such cases, you may want fsck to automatically attempt to correct the errors. This can be done with:

# fsck -y /dev/sdb

The -y flag, automatically “yes” to any prompts from fsck to correct an error.

Similarly, you can run the same on all filesystems (without root):

$ fsck -AR -y 

How to Run fsck on Linux Root Partition

In some cases, you may need to run fsck on the root partition of your system. Since you cannot run fsck while the partition is mounted, you can try one of these options:

  • Force fsck upon system boot
  • Run fsck in rescue mode

We will review both situations.

Force fsck Upon System Boot

This is relatively easy to complete, the only thing you need to do is create a file called forcefsck in the root partition of your system. Use the following command:

# touch /forcefsck

Then you can simply force or schedule a reboot of your system. During the next bootup, the fsck will be performed. If downtime is critical, it is recommended to plan this carefully, since if there are many used inodes on your system, fsck may take some extra time.

After your system boots, check if the file still exists:

# ls /forcefsck

If it does, you may want to remove it in order to avoid fsck on every system boot.

Run fsck in Rescue Mode

Running fsck in rescue mode requires a few more steps. First, prepare your system for reboot. Stop any critical services like MySQL/MariaDB etc and then type.

# reboot

During the boot, hold down the shift key so that the grub menu is shown. Select “Advanced options”.

Grub Advance Options

Grub Advanced Options

Then choose “Recovery mode”.

Select Linux Recovery Mode

Select Linux Recovery Mode

In the next menu select “fsck”.

Select fsck Utility

Select fsck Utility

You will be asked if you wish to have your / filesystem remounted. Select “yes”.

Confirm Root Filesystem

Confirm Root Filesystem

You should see something similar to this.

Running fsck Filesystem Check

Running fsck Filesystem Check

You can then resume normal boot, by selecting “Resume”.

Select Normal Boot

Select Normal Boot
Conclusion

In this tutorial, you learned how to use fsck and run consistency checks on different Linux filesystems. If you have any questions about fsck, please do not hesitate to submit them in the comment section below.

Понравилась статья? Поделить с друзьями:
  • Game exe что делать при ошибке
  • Game exe системная ошибка не удается продолжить выполнение кода
  • Game exe системная ошибка запуск программы невозможен
  • Game exe ошибка приложения 0xc0000142
  • Game exe ошибка приложения 0xc000007b