How to check a filesystem → fsck

How to Check a Filesystem → fsck Table of Contents 1. [Introduction](#introduction) 2. [Prerequisites](#prerequisites) 3. [Understanding fsck](#understanding-fsck) 4. [Basic fsck Usage](#basic-fsck-usage) 5. [Advanced fsck Options](#advanced-fsck-options) 6. [Filesystem-Specific Commands](#filesystem-specific-commands) 7. [Practical Examples](#practical-examples) 8. [Common Issues and Troubleshooting](#common-issues-and-troubleshooting) 9. [Best Practices](#best-practices) 10. [Automated Filesystem Checks](#automated-filesystem-checks) 11. [Recovery Scenarios](#recovery-scenarios) 12. [Conclusion](#conclusion) Introduction Filesystem integrity is crucial for maintaining a stable and reliable Linux system. The `fsck` (file system check) command is an essential tool that allows system administrators and users to verify and repair filesystem inconsistencies. Whether you're dealing with unexpected shutdowns, hardware failures, or routine maintenance, understanding how to properly use fsck can save your data and prevent system corruption. This comprehensive guide will walk you through everything you need to know about filesystem checking, from basic concepts to advanced recovery techniques. You'll learn when to use fsck, how to interpret its output, and how to handle various filesystem problems safely and effectively. Prerequisites Before diving into filesystem checking, ensure you have: - Root access or sudo privileges on your Linux system - Basic understanding of Linux command line interface - Knowledge of your filesystem types (ext4, xfs, btrfs, etc.) - Backup of important data (always recommended before filesystem operations) - Access to system recovery tools (live USB/CD for emergency situations) Important Safety Notes ⚠️ Warning: Never run fsck on a mounted filesystem unless it's mounted read-only. This can cause severe data corruption. ⚠️ Caution: Always backup critical data before performing filesystem repairs. Understanding fsck What is fsck? The `fsck` command is a generic frontend for various filesystem-specific checking utilities. It examines filesystems for errors and inconsistencies, and can automatically repair many common problems. The command works by: - Checking filesystem metadata structures - Verifying directory entries and inode consistency - Detecting and fixing orphaned files - Correcting filesystem size discrepancies - Repairing damaged superblocks When to Use fsck You should consider running fsck in the following situations: - System crashes or unexpected shutdowns - Boot failures with filesystem errors - Disk I/O errors reported in system logs - Routine maintenance (scheduled checks) - Before major system changes (as a precaution) - After hardware failures or disk replacements Basic fsck Usage Checking Filesystem Status Before running fsck, identify your filesystems and their current status: ```bash List all mounted filesystems df -h Show filesystem types lsblk -f Check specific partition information sudo fdisk -l ``` Basic Syntax The basic syntax for fsck is: ```bash fsck [options] [filesystem] ``` Simple Filesystem Check To perform a basic check without making repairs: ```bash Check without repairs (read-only) sudo fsck -n /dev/sda1 Check with verbose output sudo fsck -v /dev/sda1 Check and automatically fix errors sudo fsck -y /dev/sda1 ``` Understanding Exit Codes fsck returns specific exit codes that indicate the results: - 0: No errors found - 1: Filesystem errors corrected - 2: System should be rebooted - 4: Filesystem errors left uncorrected - 8: Operational error - 16: Usage or syntax error - 32: fsck canceled by user request - 128: Shared-library error Advanced fsck Options Comprehensive Option Overview ```bash Force check even if filesystem appears clean sudo fsck -f /dev/sda1 Check all filesystems in /etc/fstab sudo fsck -A Exclude specific filesystem types sudo fsck -A -t noext4,novfat Run checks in parallel for multiple filesystems sudo fsck -A -P Interactive mode (ask before each fix) sudo fsck -r /dev/sda1 ``` Detailed Option Explanations | Option | Description | Use Case | |--------|-------------|----------| | `-n` | No changes, check only | Safe diagnostic check | | `-y` | Automatic yes to all questions | Unattended repairs | | `-f` | Force check | Override clean filesystem flag | | `-v` | Verbose output | Detailed progress information | | `-r` | Interactive mode | Careful, selective repairs | | `-a` | Automatic repair (deprecated) | Legacy systems only | | `-p` | Automatic repair (safe) | Modern automatic repair | Filesystem-Specific Commands ext2/ext3/ext4 Filesystems For ext filesystems, `e2fsck` provides additional options: ```bash Check ext4 filesystem with detailed output sudo e2fsck -v /dev/sda1 Force full check regardless of clean flag sudo e2fsck -f /dev/sda1 Check bad blocks during filesystem check sudo e2fsck -c /dev/sda1 Use alternative superblock (if primary is corrupted) sudo e2fsck -b 32768 /dev/sda1 ``` XFS Filesystems XFS uses `xfs_repair` for repairs and `xfs_check` for verification: ```bash Check XFS filesystem (read-only) sudo xfs_check /dev/sda1 Repair XFS filesystem sudo xfs_repair /dev/sda1 Verbose repair with progress reporting sudo xfs_repair -v /dev/sda1 No-modify mode (check only) sudo xfs_repair -n /dev/sda1 ``` Btrfs Filesystems Btrfs has its own checking and repair tools: ```bash Check btrfs filesystem sudo btrfs check /dev/sda1 Repair btrfs filesystem (use with caution) sudo btrfs check --repair /dev/sda1 Check with detailed progress sudo btrfs check --progress /dev/sda1 ``` Practical Examples Example 1: Routine Maintenance Check ```bash #!/bin/bash Weekly filesystem maintenance script echo "Starting weekly filesystem check..." Unmount the filesystem (if possible) sudo umount /dev/sdb1 Perform comprehensive check sudo fsck -f -v /dev/sdb1 Check exit code if [ $? -eq 0 ]; then echo "Filesystem check completed successfully" elif [ $? -eq 1 ]; then echo "Filesystem errors were corrected" echo "Consider rebooting the system" else echo "Filesystem check encountered problems" echo "Manual intervention may be required" fi Remount the filesystem sudo mount /dev/sdb1 /mnt/data ``` Example 2: Emergency Boot Repair When your system won't boot due to filesystem errors: ```bash Boot from live USB/CD and run: Identify the root filesystem sudo fdisk -l Check the root filesystem sudo fsck -y /dev/sda1 If errors persist, force a thorough check sudo e2fsck -f -y /dev/sda1 For severely corrupted filesystems sudo e2fsck -b 32768 -y /dev/sda1 ``` Example 3: Checking All Filesystems ```bash Check all filesystems defined in /etc/fstab sudo fsck -A -V Skip root filesystem and check others sudo fsck -A -R -V Check only specific filesystem types sudo fsck -A -t ext4 -V ``` Common Issues and Troubleshooting Issue 1: "Filesystem is mounted" Error Problem: Attempting to run fsck on a mounted filesystem. Solution: ```bash Check if filesystem is mounted mount | grep /dev/sda1 Unmount the filesystem sudo umount /dev/sda1 If unmount fails, force unmount sudo umount -l /dev/sda1 Then run fsck sudo fsck /dev/sda1 ``` Issue 2: Corrupted Superblock Problem: Primary superblock is damaged. Solution: ```bash Find backup superblocks sudo dumpe2fs /dev/sda1 | grep superblock Use backup superblock sudo e2fsck -b 32768 /dev/sda1 Alternative backup locations sudo e2fsck -b 98304 /dev/sda1 ``` Issue 3: "Bad magic number" Error Problem: Filesystem type mismatch or severe corruption. Solution: ```bash Verify filesystem type sudo file -s /dev/sda1 Use correct filesystem checker sudo e2fsck /dev/sda1 # for ext filesystems sudo xfs_repair /dev/sda1 # for XFS sudo fsck.vfat /dev/sda1 # for FAT32 ``` Issue 4: Inode Errors Problem: Corrupted or orphaned inodes. Solution: ```bash Check and repair inodes sudo e2fsck -f /dev/sda1 If many orphaned inodes exist sudo e2fsck -y /dev/sda1 Check lost+found directory after repair ls -la /mnt/lost+found/ ``` Issue 5: Journal Errors (ext3/ext4) Problem: Journal corruption preventing filesystem mount. Solution: ```bash Remove the journal (converts ext3 to ext2 temporarily) sudo tune2fs -O ^has_journal /dev/sda1 Run fsck sudo e2fsck -f /dev/sda1 Recreate journal sudo tune2fs -j /dev/sda1 ``` Best Practices 1. Regular Maintenance Schedule Implement a regular filesystem checking schedule: ```bash Add to crontab for monthly checks 0 2 1 /usr/bin/fsck -A -R -y >> /var/log/fsck.log 2>&1 ``` 2. Monitor Filesystem Health Use system monitoring to detect issues early: ```bash Check filesystem statistics sudo tune2fs -l /dev/sda1 | grep -i error Monitor system logs for filesystem errors sudo journalctl -f | grep -i "filesystem\|fsck\|ext4" Use smartctl to monitor disk health sudo smartctl -a /dev/sda ``` 3. Backup Before Major Operations Always create backups before running fsck: ```bash Create filesystem image backup sudo dd if=/dev/sda1 of=/backup/sda1.img bs=1M Or use filesystem-aware backup sudo dump -0f /backup/sda1.dump /dev/sda1 ``` 4. Test Recovery Procedures Regularly test your recovery procedures: ```bash Create test filesystem sudo dd if=/dev/zero of=test.img bs=1M count=100 sudo mkfs.ext4 test.img Mount and add test data sudo mount test.img /mnt/test sudo cp -r /etc /mnt/test/ Simulate corruption and test recovery sudo umount /mnt/test sudo fsck test.img ``` Automated Filesystem Checks Configuring Automatic Checks Modern Linux systems can automatically check filesystems during boot: ```bash Set maximum mount count before forced check sudo tune2fs -c 20 /dev/sda1 Set check interval (180 days) sudo tune2fs -i 180d /dev/sda1 Disable automatic checks sudo tune2fs -c 0 -i 0 /dev/sda1 ``` Systemd Integration For systemd-based systems, filesystem checks are handled by systemd: ```bash Check systemd fsck services systemctl status systemd-fsck@dev-sda1.service View fsck logs journalctl -u systemd-fsck@dev-sda1.service ``` Recovery Scenarios Scenario 1: Boot Failure Due to Filesystem Corruption 1. Boot from rescue media 2. Identify the problematic filesystem 3. Run comprehensive fsck 4. Verify repair success 5. Reboot normally ```bash Complete recovery sequence sudo fdisk -l sudo fsck -y /dev/sda1 sudo mount /dev/sda1 /mnt ls -la /mnt # Verify filesystem accessibility sudo umount /mnt reboot ``` Scenario 2: Data Recovery from Corrupted Filesystem ```bash Mount filesystem read-only if possible sudo mount -o ro /dev/sda1 /mnt/recovery Copy critical data sudo cp -r /mnt/recovery/home/user/documents /backup/ Unmount and repair sudo umount /mnt/recovery sudo fsck -y /dev/sda1 Check lost+found for recovered files sudo mount /dev/sda1 /mnt/recovery ls -la /mnt/recovery/lost+found/ ``` Scenario 3: Multiple Filesystem Failures ```bash Check all filesystems sequentially for fs in /dev/sda1 /dev/sda2 /dev/sdb1; do echo "Checking $fs..." sudo fsck -y $fs echo "Exit code: $?" done ``` Performance Considerations Optimizing fsck Performance For large filesystems, consider these optimization strategies: ```bash Use multiple threads (e2fsck) sudo e2fsck -E threads=4 /dev/sda1 Skip time-consuming checks if not needed sudo e2fsck -D /dev/sda1 # Optimize directories only Use faster checking for clean filesystems sudo fsck -p /dev/sda1 ``` Monitoring Progress For long-running checks, monitor progress: ```bash Enable progress reporting sudo e2fsck -C 0 /dev/sda1 Monitor from another terminal watch -n 5 'ps aux | grep fsck' ``` Conclusion Filesystem checking with fsck is an essential skill for Linux system administration. Regular maintenance, proper understanding of filesystem types, and following best practices can prevent data loss and system instability. Remember these key points: - Always unmount filesystems before running fsck (except for read-only checks) - Backup critical data before performing repairs - Understand your filesystem type and use appropriate tools - Monitor system logs for early warning signs - Test recovery procedures regularly - Implement automated checking where appropriate By mastering fsck and related tools, you'll be well-equipped to handle filesystem issues confidently and maintain healthy Linux systems. Regular filesystem maintenance is not just about fixing problems—it's about preventing them and ensuring your system's long-term reliability and performance. Whether you're dealing with routine maintenance or emergency recovery situations, the techniques and practices outlined in this guide will help you navigate filesystem challenges effectively and safely.