Can I fix bad blocks on my hard disk with a single command?
Well, there are a couple of cases:
- This disk is part of a RAID array. Good. Just have md 'repair' the array like this:
echo 'repair' > /sys/block/md0/md/sync_action
. Problem solved without data loss. (I'm guessing this isn't the case for you, but you really ought to consider changing that.) - You don't care about the data on the disk (or there isn't any). Just use dd to zero the whole disk.
- The bad blocks are part of the free space on the disk. Use e.g.,
cat /dev/zero > tempfile
to fill the free space with zeros. Do this as root (there is space reserved for root only), probably in single-user mode (so nothing breaks from running out of space). After that runs out of space, remove the file (rm tempfile
). - The bad blocks are part of the data (files) or metadata (filesystem structure) on the disk. You have lost data.
fsck -fc
(run with the filesystem unmounted, or worst case in readonly during early boot if its the root filesystem) will tell you which files. Replace them from backup.
Its also possible that badblocks -n
, which must only be done on an unmounted filesystem, will force a remap. It shouldn't lose any data (other than what was in the bad blocks, which is already lost).
If you want to script it based on the badblocks output (which is not safe, it leaves you with silent corruption), that's fairly easy. Each line of badblocks output gives you a block number, based on your block size (512 in your example). Use the same block size for dd's bs
. The block number is your seek
for dd. Your count
is 1 (or higher, if there are a few bad blocks in a row). of
is the partition (or disk) you ran badblocks on. A good if
is /dev/zero
.