Partitioning – Copy and Edit Partition Table with sfdisk

fdiskpartition-copypartitioning

I've seen a number of variations on this, but nothing that puts all the parts together. I'm doing this on a Linux system

I know I can use sfdisk /dev/sda <table.txt to copy a partition table. Then I can use sfdisk /dev/sda <table.txt use that data to recreate the same table on a new disk.

I can also specify a partition that uses all the free space left on a disk with something like echo 'start=2048, type=83' | sudo sfdisk /dev/sdb.

What I want to do is use the first method, but edit table.txt in my batch file so the last partition in that file will now fill up all the remaining free space. This way if I'm copying a partition table to a larger or smaller sized disk, the last partition will use all available space. (We'll take as given that I'll be sure I'm not copying more data to the source than the new drive can hold if it's a smaller size than the original.)

For example, if I have a table like this:

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

/dev/sda1 : start=        8192, size=      524288, type=e, bootable
/dev/sda2 : start=      532480, size=   245227520, type=83

What do I do for the size for /dev/sda2 to specify to use the rest of the free space for it? I tried specifying a 0, -1, and nothing for the size value for that partition and none of them worked.

My goal is to have a subroutine as part of a bash script that will read the partition table from one drive, make the change I've mentioned (with something like sed or awk) in the file, then use the edited file to create a partition table on a second drive that will will make the last partition as big as possible. While I was thinking this would be fairly easy to do the way I'm describing, I'm open to other ways to do this as well.

Best Answer

while sfdisk is great for cloning a partition table without modification, I would recommend switching to using parted if you want to alter some partitions.

I don't know how to clone a partition table with parted so I'd keep sfdisk for that part:

sfdisk -d /dev/sourcedisk | sfdisk /dev/newdisk

The next lines in your batch script could make use of the command parted resizepart to use all the available space on the new disk.

parted /dev/newdisk -s resizepart 2 100%

Related Question