Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have an ext4 filesystem that recently developed some bad sectors. Running fsck.ext4 -c finds and remembers the bad blocks. How can I find which files (if any) included these bad blocks so I can restore them from backups?

share|improve this question

migrated from stackoverflow.com Apr 23 '12 at 13:24

This question came from our site for professional and enthusiast programmers.

1 Answer 1

With a combination of dumpe2fs and debugfs, which are included in the e2fsprogs package as fsck.ext*.
You must use the output of a command as the argument of the next one.
These tools auto-detect the filesystem block size, so it is consistent and safer than direct bad blocks invocation.

Prints the registered bad blocks of the filesystem:

# dumpe2fs -b DEVNAME

Prints the inodes which use the given block list:

# debugfs -R "icheck BLOCK ..." DEVNAME

Prints the pathnames to the given inode list:

# debugfs -R "ncheck INODE ..." DEVNAME

debugfs has also an interactive shell and the -f cmd_file option, but they are not much powerful or useful for this case.
The -R option allows more automated scripts like this:

#!/bin/sh
# Valid only for ext* filesystems with badblocks registered by
# fsck -c [-c] [-k] or -l|L options.

DEVNAME="$1"
[ -b "$DEVNAME" ] || exit 1

BADBLOCKS="$(dumpe2fs -b "$DEVNAME" | tr '\n' ' ')"
[ -n "$BADBLOCKS" ] || exit 0

# Equivalent but slower: tail -n +2 | awk '{ print $2 }' | sort -u | tr '\n' ' '
FILTER='NR >= 2 { uniq[$2] = "" } END { for (inode in uniq) printf inode OFS }'
INODES="$(debugfs -R "icheck $BADBLOCKS" "$DEVNAME" | awk "$FILTER")"
[ -n "$INODES" ] || exit 0

debugfs -R "ncheck -c $INODES" "$DEVNAME"
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.