Skip to content

Instantly share code, notes, and snippets.

@SteveDevOps
Last active July 13, 2023 16:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SteveDevOps/adf1164dc8cc231b5a77c43d15a4e6da to your computer and use it in GitHub Desktop.
Save SteveDevOps/adf1164dc8cc231b5a77c43d15a4e6da to your computer and use it in GitHub Desktop.
fix corrupted sdcard

fix corrupted sd card with bad superblock

unmount

sudo umount /dev/mmcblk0p1

get the superblock backup block ids

sudo mke2fs -n /dev/mmcblk0p1

fix and restore from backup block

sudo e2fsck -y -b <backup superblock id> /dev/mmcblk0p1

check if clean / fix

sudo e2fsck -p /dev/mmcblk0p1

or

sudo e2fsck -y /dev/mmcblk0p1

script

#!/bin/bash

# Ensure script is run as root or with sudo
if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root or with sudo." 
   exit 1
fi

# Check if a device path is provided as an argument
if [ -z "$1" ]; then
    echo "Usage: $0 /dev/sdX"
    exit 1
fi

device=$1

# Verify that the device exists
if [ ! -b "$device" ]; then
    echo "The specified device $device does not exist."
    exit 1
fi

# Verify that the partition exists
if [ ! -e "${device}1" ]; then
    echo "The specified partition ${device}1 does not exist."
    exit 1
fi

# Unmount the partition if it is mounted
umount "${device}1"

# Attempt to repair the filesystem using fsck
fsck -y "${device}1"

# Check if the fsck command succeeded
if [ $? -eq 0 ]; then
    echo "The filesystem on ${device}1 has been repaired successfully."
else
    # If fsck failed, attempt to restore the superblock
    superblocks=$(dumpe2fs -h "${device}1" | grep "Backup superblock" | awk '{print $4}')
    restore_successful=false

    for sb in $superblocks
    do
        fsck -b $sb "${device}1"

        # Check if the fsck command succeeded
        if [ $? -eq 0 ]; then
            echo "The superblock on ${device}1 has been restored successfully using backup superblock $sb."
            restore_successful=true
            break
        fi
    done

    if [ "$restore_successful" = false ]; then
        echo "Failed to repair the filesystem or restore the superblock on ${device}1."
        echo "Please consider data recovery options or consult a professional."
        exit 1
    fi
fi

# Attempt to mount the repaired partition
mount "${device}1" >/dev/null 2>&1

# Check if the mount command succeeded
if [ $? -eq 0 ]; then
    echo "The partition ${device}1 has been successfully mounted."
else
    echo "Failed to mount the partition ${device}1."
    echo "Please check the filesystem manually or consult a professional."
    exit 1
fi

exit 0


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment