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

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

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.

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 с примерами.

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

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

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

Немного теории

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

Современные файловые системы делятся на два типа — журналируемые и нежурналируемые. Журналиуемые файловые системы записывают в лог все действия, которые собираются выполнить, а после выполнения стирают эти записи. Это позволяет очень быстро понять была ли файловая система повреждена. Но не сильно помогает при восстановлении. Чтобы восстановить файловую систему linux необходимо проверить каждый блок файловой системы и найти поврежденные сектора.

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

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

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

А теперь давайте рассмотрим сам синтаксис утилиты:

$ fsck [опции] [опции_файловой_системы] [раздел_диска]

Основные опции указывают способ поведения утилиты, оболочки fsck. Раздел диска — это файл устройства раздела в каталоге /dev, например, /dev/sda1 или /dev/sda2. Опции файловой системы специфичны для каждой отдельной утилиты проверки.

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

  • -l — не выполнять другой экземпляр fsck для этого жесткого диска, пока текущий не завершит работу. Для SSD параметр игнорируется;
  • -t — задать типы файловых систем, которые нужно проверить. Необязательно указывать устройство, можно проверить несколько разделов одной командой, просто указав нужный тип файловой системы. Это может быть сама файловая система, например, ext4 или ее опции в формате opts=ro. Утилита просматривает все файловые системы, подключенные в fstab. Если задать еще и раздел то к нему будет применена проверка именно указанного типа, без автоопределения;
  • -A — проверить все файловые системы из /etc/fstab. Вот тут применяются параметры проверки файловых систем, указанные в /etc/fstab, в том числе и приоритетность. В первую очередь проверяется корень. Обычно используется при старте системы;
  • -C — показать прогресс проверки файловой системы;
  • -M — не проверять, если файловая система смонтирована;
  • -N — ничего не выполнять, показать, что проверка завершена успешно;
  • -R — не проверять корневую файловую систему;
  • -T — не показывать информацию об утилите;
  • -V — максимально подробный вывод.

Это были глобальные опции утилиты. А теперь рассмотрим опции для работы с файловой системой, их меньше, но они будут более интересны:

  • -a — во время проверки исправить все обнаруженные ошибки, без каких-либо вопросов. Опция устаревшая и ее использовать не рекомендуется;
  • -n — выполнить только проверку файловой системы, ничего не исправлять;
  • -r — спрашивать перед исправлением каждой ошибки, используется по умолчанию для файловых систем ext;
  • -y — отвечает на все вопросы об исправлении ошибок утвердительно, можно сказать, что это эквивалент a.
  • -c — найти и занести в черный список все битые блоки на жестком диске. Доступно только для ext3 и ext4;
  • -f — принудительная проверка файловой системы, даже если по журналу она чистая;
  • -b — задать адрес суперблока, если основной был поврежден;
  • -p — еще один современный аналог опции -a, выполняет проверку и исправление автоматически. По сути, для этой цели можно использовать одну из трех опций: p, a, y.

Теперь мы все разобрали и вы готовы выполнять восстановление файловой системы linux. Перейдем к делу.

Как восстановить файловую систему в fsck

Допустим, вы уже загрузились в LiveCD систему или режим восстановления. Ну, одним словом, готовы к восстановлению ext4 или любой другой поврежденной ФС. Утилита уже установлена по умолчанию во всех дистрибутивах, так что устанавливать ничего не нужно.

Восстановление файловой системы

Если ваша файловая система находится на разделе с адресом /dev/sda1 выполните:

sudo fsck -y /dev/sda1

fsck3

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

Восстановление поврежденного суперблока

Обычно эта команда справляется со всеми повреждениями на ура. Но если вы сделали что-то серьезное и повредили суперблок, то тут fsck может не помочь. Суперблок — это начало файловой системы. Без него ничего работать не будет.

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

sudo mkfs -t ext4 -n /dev/sda1

fsck1

На самом деле эта команда создает новую файловую систему. Вместо ext4 подставьте ту файловую систему, в которую был отформатирован раздел, размер блока тоже должен совпадать иначе ничего не сработает. С опцией -n никаких изменений на диск не вноситься, а только выводится информация, в том числе о суперблоках.

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

sudo fsck -b 98304 /dev/sda1

fsck2

После этого, скорее всего, вам удастся восстановить вашу файловую систему. Но рассмотрим еще пару примеров.

Проверка чистой файловой системы

Проверим файловую систему, даже если она чистая:

sudo fsck -fy /dev/sda1

fsck4

Битые сектора

Или еще мы можем найти битые сектора и больше в них ничего не писать:

sudo fsck -c /dev/sda1

fsck5

Установка файловой системы

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

sudo fsck -t ext4 /dev/sdb1

fsck6

Проверка всех файловых систем

С помощью флага -A вы можете проверить все файловые системы, подключенные к компьютеру:

sudo fsck -A -y

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

sudo fsck -AR -y

Или исключить все примонтированные файловые системы:

sudo fsck -M -y

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

sudo fsck -A -t ext4 -y

Или можно также фильтровать по опциям монтирования в /etc/fstab, например, проверим файловые системы, которые монтируются только для чтения:

sudo fsck -A -t opts=ro

Проверка примонтированных файловых систем

Раньше я говорил что нельзя. Но если другого выхода нет, то можно, правда не рекомендуется. Для этого нужно сначала перемонтировать файловую систему в режим только для чтения. Например:

sudo mount -o remount,ro /dev/sdb1

А теперь проверка файловой системы fsck в принудительном режиме:

sudo fsck -fy /dev/sdb1

fsck7

Просмотр информации

Если вы не хотите ничего исправлять, а только посмотреть информацию, используйте опцию -n:

sudo fsck -n /dev/sdb1

fsck8

Выводы

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

На десерт сегодня видео на английском про различия файловых систем ext4 и xfs, как обычно, есть титры:

https://www.youtube.com/watch?v=pECp066gGcY

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

An operating system user that is still a learner in the OS world can never escape the challenges the current elite users have overcome. The user impact of such challenges depends on the operating system flavor or distribution you are under.

For Linux users, you might think you are facing an impossible challenge only to realize that there are multiple valid solutions for every single OS problem faced.

[ You might also like: How to Backup Linux Filesystem Using dump Command ]

The Linux file system is a maze that most users hesitate to enter. It is because this file system is responsible for the performance consistency of your Linux operating system and any slight modification to its hierarchy or file system structure can be a nightmare for any user.

The FSCK Linux Command

The Linux operating system handles file system issues through the fsck command-line utility. It is a prepackaged file system check toolkit that interactively checks and repairs corrupted files that might affect the performance of your operating system.

$ man fsck

Most of the time, it is these corrupt files that are responsible for failed system boots and partition mounts.

FSCK Command Usage

The standard syntax for fsck command-line utility is as follows:

# fsck [OPTIONS] [FILESYSTEM]

You need to be a sudoer user or have sudo privileges to effectively use the FSCK tool.

FSCK adheres to some predefined rules.

  • It references the /etc/fstab file when a user does not provide [FILESYSTEM] as a command argument.

Linux fstab File

Linux fstab File

The <pass> column for the <mount point> (/) and <type> (ext4) is set to 1 because its file system checks and repair are prioritized.

It is not recommended to use the fsck command with mounted partitions as there is a high likelihood of permanent file system damage.

Repairing A Corrupted Linux File System

The first step is to identify the device partition that holds the Linux file system you would like to check and repair.

$ sudo fdisk -l

List Linux File System Partitions

List Linux File System Partitions

The second step is to unmount the device whose file system you want to check and repair. e.g.

$ sudo umount /dev/sda5

The third step is to check and possibly repair the device’s file system using FSCK.

$ sudo fsck -p /dev/sda5 

The -p command option is for automatic repair without any user intervention.

The final step is to re-mount your device once the fsck file system check and repair is complete.

$ sudo mount /dev/sda5 

Repairing Linux File System on Boot-Time

On a running machine, it is not possible to simultaneously check and repair your Linux file system while using the OS. In this case, we have the options of using a live CD/bootable usb drive or checking and repairing the Linux file system on boot (For installed Linux systems).

Linux File System Repair on Boot

1. Restart your machine, press [Esc] or [Shift] and select Advanced Options on the resulting boot menu.

Ubuntu Advanced Options

Ubuntu Advanced Options

2. Select Recovery Mode and choose the fsck option from the resulting list of menu options.

Ubuntu Recovery Mode

Ubuntu Recovery Mode

3. Hit [Enter] and choose the fsck menu option.

Ubuntu Fsck Option

Ubuntu Fsck Option

4. Choose Yes when asked whether to remount your OS root file system.

Mount Ubuntu Filesystem

Mount Ubuntu Filesystem

5. Once the file system check and repair is complete, direct your system to resume normal boot.

Resume Ubuntu Normal Boot

Resume Ubuntu Normal Boot

Live CD/USB File System Repair

  1. Boot into your machine from the live distribution (CD or USB).
  2. Open the Linux terminal and use sudo fdisk -l command to find the targeted Linux root partition name.
  3. If the root partition is identified by a name like /dev/sda1, running the following command will check and possibly repair its associated file system.
$ sudo fsck -p /dev/sda1 

FSCK is a very effective tool to get you started on understanding the nature and performance of your Linux system. The man fsck command has more options on using the FSCK utility to check and optionally repair broken or corrupt Linux file systems.

Photo of author

I am an Experienced GNU/Linux expert and a full-stack software developer with over a decade in the field of Linux and Open Source technologies.
Founder of TecMint.com, LinuxShellTips.com, and Fossmint.com. Over 150+ million people visited my websites.


Each tutorial at UbuntuMint is created by a team of experienced writers so that it meets our high-quality standards.

Was this article helpful? Please add a comment to show your appreciation and support.

Понравилась статья? Поделить с друзьями:
  • Ubuntu постоянные ошибки
  • Unb ошибка на стиральной машине haier что делать
  • Ubuntu ошибки apache
  • Unb ошибка на стиральной машине haier как сбросить
  • Ubuntu ошибка репозиториев