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

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.

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

how-to-scan-and-repair-linux-disk-errors

In this article, you will learn how to repair Linux disk errors by using fsck and xfs_repair commands.

Table of Contents:

  • What is FSCK?
  • List Linux Disk Partitions and Types
  • Get Last Scanned Time of a Linux Disk
  • Scan & Repair a Ext4 Type Disk Partition
  • Enable Scanning of Ext4 Disk Partitions at Linux Startup
  • What is XFS_REPAIR?
  • Scan & Repair a XFS Type Disk Partition
  • Enable Scanning of XFS Disk Partitions at Linux Startup
  • Conclusion

What is FSCK?:

The system utility fsck (file system consistency check) is a tool for checking the consistency of a file system in Unix and Unix-like operating systems, such as Linux, macOS, and FreeBSD.

Generally, fsck is run either automatically at boot time, or manually by the system administrator. The command works directly on data structures stored on disk, which are internal and specific to the particular file system in use — so an fsck command tailored to the file system is generally required. The exact behaviors of various fsck implementations vary, but they typically follow a common order of internal operations and provide a common command-line interface to the user. (Source: Wikipedia)

how-to-scan-and-repair-linux-disk-errors

List Linux Disk Partitions and Types:

First of all you need to identify the disk partitions in your Linux server, their respective file systems and the path where they are being mounted.

If you are not used to Linux commandline then we recommend that you should attend online training Linux Command Line: From novice to wizard

By using a console or a ssh client, connect with your Linux server as root user.

You can execute the lsblk command with following switches at the Linux bash prompt to list the required information.

# lsblk -o NAME,FSTYPE,MOUNTPOINT
NAME        FSTYPE      MOUNTPOINT
sda
├─sda1      ext4        /boot
└─sda2      LVM2_member
  ├─cl-root xfs         /
  ├─cl-swap swap        [SWAP]
  └─cl-home xfs         /home
sr0

Get Last Scanned Time of a Linux Disk:

You can find the last scan time for Linux Ext4 type partitions with the help of following command.

# tune2fs -l /dev/sda1 | grep checked
Last checked:             Sun Sep 29 20:03:14 2019

Scan & Repair a Ext4 Type Disk Partition:

To scan a Linux disk partition, you can use fsck (File System Consistency Check) command. But you are required to unmount that partition before checking and repairing it.

# umount /dev/sda1

After successful unmount, execute fsck command at Linux bash prompt.

# fsck.ext4 /dev/sda1
e2fsck 1.45.6 (20-Mar-2020)
/dev/sda1: clean, 320/65536 files, 61787/262144 blocks

After checking and repairing your Linux disk, mount the partition again at its respective mountpoint.

For this purpose, execute following Linux command to mount all the disk partitions listed in /etc/fstab file.

# mount -a

Enable Scanning of Ext4 Disk Partitions at Linux Startup:

To enable disk checking at the time of Linux startup. You have to modify the Mount Count parameter for that disk partition.

# tune2fs -c 1 /dev/sda1
tune2fs 1.45.6 (20-Mar-2020)
Setting maximal mount count to 1

Reboot your Linux server now.

# reboot

Linux command fsck is now check your Ext4 disk partition on startup.

After reboot, get the Last Checked value for your disk partition, now it will show you the time of last Linux startup.

# tune2fs -l /dev/sda1 | grep checked
Last checked:             Sun Aug  1 22:50:46 2021

Set back the Mount Count parameter, or it will keep performing disk scans on each Linux boot.

# tune2fs -c -1 /dev/sda1
tune2fs 1.45.6 (20-Mar-2020)
Setting maximal mount count to -1

What is XFS_REPAIR?:

XFS is a high-performance 64-bit journaling file system created by Silicon Graphics, Inc (SGI) in 1993. It was the default file system in SGI’s IRIX operating system starting with its version 5.3. XFS was ported to the Linux kernel in 2001; as of June 2014, XFS is supported by most Linux distributions, some of which use it as the default file system.

The xfs_repair utility is highly scalable and is designed to repair even very large file systems with many inodes efficiently. Unlike other Linux file systems, xfs_repair does not run at boot time, even when an XFS file system was not cleanly unmounted. In the event of an unclean unmount, xfs_repair simply replays the log at mount time, ensuring a consistent file system.

Scan & Repair a XFS Type Disk Partition:

XFS type disk partitions have their own set of commands, that are a little bit different from Ext4.

You must unmount a XFS disk partition before checking it for consistency.

# umount /dev/mapper/cl-home

We have xfs_repair command for checking and repairing the disk errors.

In some Linux distros, you may also find xfs_check command. This command only perform scanning of XFS type disk partitions and do not perform any repair.

But xfs_check command is not available in all Linux distros.

Alternatively, you can use xfs_repair command with -n switch to get the same functionality as of xfs_check.

# xfs_repair -n /dev/mapper/cl-home
Phase 1 - find and verify superblock...
Phase 2 - using internal log
        - zero log...
        - scan filesystem freespace and inode maps...
        - found root inode chunk
Phase 3 - for each AG...
        - scan (but don't clear) agi unlinked lists...
        - process known inodes and perform inode discovery...
        - agno = 0
        - agno = 1
        - agno = 2
        - agno = 3
        - process newly discovered inodes...
Phase 4 - check for duplicate blocks...
        - setting up duplicate extent list...
        - check for inodes claiming duplicate blocks...
        - agno = 0
        - agno = 1
        - agno = 2
        - agno = 3
No modify flag set, skipping phase 5
Phase 6 - check inode connectivity...
        - traversing filesystem ...
        - traversal finished ...
        - moving disconnected inodes to lost+found ...
Phase 7 - verify link counts...
No modify flag set, skipping filesystem flush and exiting.

The above command only perform disk checking and do not try to repair any error.

Now, execute the xfs_repair command without -n switch and it will perform scanning and repairing of Linux disk partitions.

# xfs_repair /dev/mapper/cl-home
Phase 1 - find and verify superblock...
Phase 2 - using internal log
        - zero log...
        - scan filesystem freespace and inode maps...
        - found root inode chunk
Phase 3 - for each AG...
        - scan and clear agi unlinked lists...
        - process known inodes and perform inode discovery...
        - agno = 0
        - agno = 1
        - agno = 2
        - agno = 3
        - process newly discovered inodes...
Phase 4 - check for duplicate blocks...
        - setting up duplicate extent list...
        - check for inodes claiming duplicate blocks...
        - agno = 0
        - agno = 1
        - agno = 2
        - agno = 3
Phase 5 - rebuild AG headers and trees...
        - reset superblock...
Phase 6 - check inode connectivity...
        - resetting contents of realtime bitmap and summary inodes
        - traversing filesystem ...
        - traversal finished ...
        - moving disconnected inodes to lost+found ...
Phase 7 - verify and correct link counts...
done

Remount the XFS partition at its original mountpoint as listed in /etc/fstab file.

# mount -a

Enable Scanning of XFS Disk Partitions at Linux Startup:

In some scenarios you cannot unmount a disk partition, if the disk is in use by the Linux operating system. For this reason you may have to defer the disk checking until next system boot.

To enable xfs_repair command to run on Linux startup, add «fsck.mode=force fsck.repair=yes» at the end of GRUB menu kernel command.

You can refer to our previous post about Editing GRUB menu.

After Linux startup, check the system log to verify the execution of disk repair command.

# journalctl | grep  systemd-fsck

To permanently enable disk checking at startup, you have to add «fsck.mode=force fsck.repair=yes» in GRUB configuration files.

Edit grub configuration file in vim text editor.

# vi /etc/default/grub

Locate GRUB_CMDLINE_LINUX parameter and append «fsck.mode=force fsck.repair=yes» at the end of line.

GRUB_CMDLINE_LINUX="resume=/dev/mapper/cl-swap rd.lvm.lv=cl/root rd.lvm.lv=cl/swap rhgb quiet fsck.mode=force fsck.repair=yes"

Regenerate GRUB menu configurations based on new parameters.

# grub2-mkconfig

Reboot your Linux operating system to verify the new settings.

# reboot

Conclusion:

You have successfully performed scanning and repairing of Linux Disk partitions of Ext4 and XFS types. If you feel any difficulty understanding this Linux tutorial, we suggest that you should read The Linux Command Line, 2nd Edition by William Shotts.

Состояние перевода: На этой странице представлен перевод статьи 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/раздел

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.

Понравилась статья? Поделить с друзьями:
  • Как проверить файл excel на ошибки
  • Как проверить текст на синтаксические ошибки
  • Как проверить файл ворд на наличие ошибок
  • Как проверить телефон на ошибки samsung
  • Как проверить файл sitemap xml на ошибки