automated disk partitioning with sfdisk

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
This entry was posted in sysadmin and tagged . Bookmark the permalink.

4 Responses to automated disk partitioning with sfdisk

  1. tsaavik says:

    Yeah sfdisk is pretty trick! I actually used it back in the day @ mp3 for flipping our file system partition type from ext2 to reiserfs in our kickstart scripts.

    #!/bin/sh
    
    ### Need to compile reiser tools before this will work
    
    # Formats /usr1 as a reiserfs partition
    # creates a swap partition
    
    #detect drive interface type
    grep 301 /proc/cmdline >/dev/null && export DTYPE=hda DPART=hda3
    grep 801 /proc/cmdline >/dev/null && export DTYPE=sda DPART=sda3
    
    #Make /usr1 reiserfs
    umount /usr1 && \
    /sbin/sfdisk –change-id /dev/$DTYPE 3 83 && \
    echo "y" | /sbin/mkreiserfs -q /dev/$DPART || exit 1
    
  2. Anonymous says:

    Could it be that the last line of your posting is missing the input redirection of the previously generated partition file?

    So this erroneous line:
    sfdisk /dev/sdc
    should better read:
    sfdisk /dev/sdc < partition.sfdisk

    Nevertheless, thanks a lot for your blog!
    Cheers,
    Gerhard

  3. Anonymous says:

    Thanks, this will come in handy. :)

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>