Using sfdisk to recover a partition table on Linux

As he re-entered the sfdisk dump manually in the remote recovery console, using the devil’s editor (vi), he was silently thanking the Linux developers for not screwing around with the file system when it cannot be mounted.

Messing around with partition tables, disk volumes, and similar critical configuration parameters can lead to quite unexpected and unintended results. So, it may be a good idea to actually dump the current configuration before you begin your magic.

Using sfdisk, you can dump your Linux partition configuration in a fairly straightforward way. You can try the command by typing just sfdisk -d /dev/disk, where disk is one of the disks in your Linux system. For a list of disks in your system, use the lsblk command. They are identified as “disk” (surprise).

sfdisk -d /dev/sda > sda.txt

This would dump the partition table data for the /dev/sda disk to the file sda.txt. Your output will look something like this:

label: dos
label-id: 0xa828a5d8
device: /dev/sda
unit: sectors

/dev/sda1 : start= 2048, size= 997376, type=83, bootable
/dev/sda2 : start= 999424, size= 999424, type=82
/dev/sda3 : start= 1998848, size= 249659359, type=83

The partition table information can then later be restore by issuing the reverse, i.e.

sfdisk /dev/sda < sda.txt

DO NOT PERFORM THE ABOVE COMMAND IF YOU DON’T KNOW WHAT YOU ARE DOING!

This procedure may come in handy if you, like me, manage to screw up the partition table and find yourself at the (initramfs) prompt when you restart your Linux machine. You will (obviously) need to save the dump file (sda.txt above) in a location other than your computer. Using this method, it’s often possible to recover your partition table from a rescue boot (be it on CD, DVD or a flash drive).

I happened to have a previous terminal session window open with the above information, so I hand-typed it from one window to another, where I was running the remote recovery console.

There are a lot more complex partition setups than the above, and sfdisk may not work in those cases or for certain RAID and LVM setups. But it it’s a good procedure in applicable situations.

Leave a Reply

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

Notify me of followup comments via e-mail. You can also subscribe without commenting.