2012-11-07

Recover partition table from running kernel

As Lady Luck would have it, during my second day on the job I inadvertently typed “sda” instead of “sdb” and overwrote the partition table of a boot drive. It was only a testing machine, but still it was something that should never happen.

Fortunately, I was able to recover it by following the instructions in Gilles’ answer at:

Recover partition table still present in running system

It was a somewhat nuanced process, though, so I’ll document it here:
# # I had two partitions: sda1 was swap and sda2 was the system
# # Of course, I had no idea how big the partitions were. Turns
# # out the kernel has this information stored:
# cat /sys/block/sda/sda1/start
2048
# cat /sys/block/sda/sda1/size
8384512
# Adding 2048 + 8384512, you get the start of the next partition
# cat /sys/block/sda/sda2/start
8386560
# cat /sys/block/sda/sda2/size
304193536

This information should be enough to re-create the partition table on the drive. However, due to an off-by-one bug (?) in fdisk, I had to decrement the sizes by one when creating the new partitions:
fdisk example here

Nevertheless, it worked! I was able to reboot the machine and everything was as before.

Good to reboot to a Live CD and run fsck on the partitions as well.


No comments:

Post a Comment