Monday, September 7, 2015

Automated partition creation with fdisk and sfdisk

To perform automated partition creation or modification you can pass all the commands via echo directly to fdisk:

echo -e "o\nn\np\n1\n\n\nw" | fdisk /dev/sdc

The commands are:
o - create a new empty DOS partition table
n - add a new partition
p - create primary partition
(enter) - set first cylinder to the default value (1)
(enter) - set the last cylinder to the default value (end of the drive)
w - write table to disk and exit

Quick way to clone partition table from one drive to another

You can use sfdisk to save the partition table from the already prepared drive and copy it to another.

As you can see below "-d" option will create a text file which can be easily altered if needed.

[root@centos ~]# sfdisk -d /dev/sdb > file

[root@centos ~]# cat file
# partition table of /dev/sdb
unit: sectors

/dev/sdb1 : start=       63, size=  1044162, Id=83
/dev/sdb2 : start=        0, size=        0, Id= 0
/dev/sdb3 : start=        0, size=        0, Id= 0
/dev/sdb4 : start=        0, size=        0, Id= 0

[root@centos ~]# sfdisk /dev/sdc < file
# sfdisk /dev/sdc < file
Checking that no-one is using this disk right now ...

Disk /dev/sdc: 65 cylinders, 255 heads, 63 sectors/track
 /dev/sdc: unrecognized partition table type
Old situation:
No partitions found
New situation:
Units = sectors of 512 bytes, counting from 0

   Device Boot    Start       End   #sectors  Id  System
/dev/sdc1            63   1044224    1044162  83  Linux
/dev/sdc2             0         -          0   0  Empty
/dev/sdc3             0         -          0   0  Empty
/dev/sdc4             0         -          0   0  Empty
Warning: no primary partition is marked bootable (active)
This does not matter for LILO, but the DOS MBR will not boot this disk.
Successfully wrote the new partition table

Re-reading the partition table ...

If you created or changed a DOS partition, /dev/foo7, say, then use dd(1)
to zero the first 512 bytes:  dd if=/dev/zero of=/dev/foo7 bs=512 count=1
(See fdisk(8).)

No comments:

Post a Comment