Command-Line Partition – How to Copy the Partition Layout of a Whole Disk Using Standard Tools

command linepartition

I want to take a backup of the whole partition layout of a hard drive, including logical drives, so that I can restore that layout to another disk. I do not want to copy the contents of the partitions, only the layout. For the primary and extended partitions, it's easy:

dd if=/dev/sda of=partitiontable.bin bs=1 skip=446 count=64 # backup
dd if=partitiontable.bin of=/dev/sda bs=1 seek=446 count=64 # restore

But when it comes to the layout of the logical partitions, I wonder if there exists among the standard tools a similar way of saving the layout? I guess the main problem is finding the offsets to the locations of the EBRs, because with that, dd will do the rest. Keep in mind I need to be able to put everything back to a (possibly) blank disk and thereby restore the same layout. Using partitioning tools like fdisk or parted is fine, but I must be able to automate their use (scripting) and they should not depend on any X-related packages — command line only.

My backup plan is doing it manually in a little python script using the struct module, but I rather hoped there was an easier way.

Best Answer

You can use sfdisk for this task even in GPT partitioned disks*.

Save:

sfdisk -d /dev/sdX > part_table

Restore keeping the same disk & partition IDs**:

sfdisk /dev/sdX < part_table

Restore generating new disk & partition IDs**:

grep -v ^label-id part_table | sed -e 's/, *uuid=[0-9A-F-]*//' | sfdisk /dev/sdY

Notes

*: For GPT partition tables, this requires sfdisk from util-linux 2.26 or later. It was re-written from scratch on top of libfdisk.

**: by default sfdisk will copy the disk and partition IDs unchanged, rather than generating new ones. So the new disk will be a clone of the original, not just another disk with the same layout. Note that Linux's /dev/disk/by-uuid/ looks at filesystem UUIDs, though, not UUIDs in the partition table. sfdisk will generate new UUIDs if you delete the references to partitions ids (, uuid=...) and the reference to the disk id (label-id: ...) from the dump .

Related Question