Backing up and restoring partition tables on Linux hosts


I recently had to adjust the partition layout on a couple of disk drives. This work occurred on devices with actual data (I made backups before starting), so I needed to be extra careful while performing my work. To ensure that I could recover the data if something went wrong with the partitioning, I made backups of each partition prior to beginning work. Assuming you are using a DOS (MBR) labeled disk, there are two ways to back up the partition table:

  1. Use dd to archive sector 0 to a safe location
  2. Archive the partition table to a safe location with parted or sfdisk

To backup a device using option 1, you can use a dd statement similar to the following:

$ dd if=/dev/sda of=/backups/sda.sector0 count=1

To restore the partion table using dd, you can can alter the dd source and destination like so:

$ dd if=/backups/sda.sector0 of=/dev/sda count=1

While this approach works well, I tend to prefer the second method. There are a couple of reasons for this:

  1. If you botch the dd statement, you can overwrite actual data making recovery extremely difficult (thank goodness for tools like ext3grep!)
  2. The MBR contains code as well as the partition table, so you can’t easily view the partion table if you run into issues

To use sfdisk to backup the partition table, you can run sfdisk with the “-d” (dump the partion table in a format that be easily consumed in the future) option and the device to extract the partion table from:

$ sfdisk -d /dev/sda > /backups/sda.ptbl

$ cat /backups/sda.ptbl

# partition table of /dev/sda
unit: sectors

/dev/sda1 : start= 63, size=479987329, Id=83, bootable
/dev/sda2 : start=479987392, size= 8388608, Id=83
/dev/sda3 : start= 0, size= 0, Id= 0
/dev/sda4 : start= 0, size= 0, Id= 0

If for some reason you botch the partition table, you can feed the partion table as input to sfdisk:

$ sfdisk /dev/sda < /backups/sda.ptbl

The second approach has the added benefit that you can review the partition table with a pager while you are making changes, which is especially useful when you grow a LUN and need to use the new space. sfdisk and parted are extremely handy tools, but you should use them with extreme caution! One wrong move can nuke your data, and the author is not responsible for any damage that you may cause to your systems as a result of this post!

This article was posted by Matty on 2009-08-06 10:20:00 -0400 -0400