automated disk partitioning with sfdisk

published on 2009-01-04 in computing

I discovered sfdisk a few years ago (part of util-linux) and have been using it in automation scripts ever since.  sfdisk is like fdisk, but is scriptable.  So for example, to list the partitions on a disk:

[root@host]# sfdisk -l /dev/sdc

Disk /dev/sdc: 121601 cylinders, 255 heads, 63 sectors/track  
Units = cylinders of 8225280 bytes, blocks of 1024 bytes, counting from
0

Device Boot Start End #cyls #blocks Id System  
/dev/sdc1 0+ 121600 121601- 976760001 83 Linux  
/dev/sdc2 0 - 0 0 0 Empty  
/dev/sdc3 0 - 0 0 0 Empty  
/dev/sdc4 0 - 0 0 0 Empty

To list them in a dump format, suitable as input to sfdisk (for cloning, saving or for some wacky awesome script):

[root@host ]# sfdisk -d /dev/sdc# partition table of /dev/sdc  
unit: sectors

/dev/sdc1 : start= 63, size=1953520002, Id=83  
/dev/sdc2 : start= 0, size= 0, Id= 0  
/dev/sdc3 : start= 0, size= 0, Id= 0  
/dev/sdc4 : start= 0, size= 0, Id= 0

You can use that dump in a fashion like this to clone a disks's partition map:

sfdisk -d /dev/sdc | sfdisk /dev/sdd

Or for saving it and using it later:

sfdisk -d /dev/sdc > partition.sfdisk  
...  
sfdisk /dev/sdc < partition.sfdisk
Tags: sysadmin