Getting a list of affect files on a BTRFS partition with corrupted blocks

I’m not a big fan of BTRFS, but I happen to have it on one of my systems. And the SSD on this system happens to be of the cheapest kinds out there, and it started to fail by silently corrupting data without any S.M.A.R.T. warning.

BTRFS has a scrub command which adequately looks for corrupted blocks (by CRC), and attempts to recover these blocks if possible (e.g. in certain RAID configurations), but my SSD is a single sad device.

OK, perhaps some of the corrupted files can be replaced by some other means (read: manually), but surprisingly, this scrub does not show which files are affected by a corrupted block which couldn’t be recovered.

Actually there is no way to find out which files are damaged using a btrfs tool.
And while some online posts say that the affected files can be deduced from error messages shown in the journal log, it seems that such information is outdated.

After some tinkering and researching I came up with the following code, which attempts to open and read every file on disk, and, if this fails, the file’s path is saved into a text file:

last_time=0
while IFS= read -r -d '' file; do
  current_time=$(date +%s)
  if (( current_time - last_time >= 1 )); then
    echo "Testing: $file"
    last_time=$current_time
  fi
  cp "$file" /dev/null 2>/dev/null || echo "$file" >> corrupted-files.txt
done < <(find / -xdev -type f -print0)

Thanks to duck.ai for making it easier than ever to use powerful LLMs privately.

Leave a Reply

Your email address will not be published. Required fields are marked *