How to run fdisk in non-interactive batch mode

Last updated on September 30, 2020 by Dan Nanni

fdisk is a command-line utility for disk partition management. It's not common that you want to automate fdisk (i.e., running fdisk in a batch mode), since (re)-partitioning your system is a rare thing, and you typically deal with a small number of partitions at once. However, if you try to automate virtual machine creation, partitioning and formatting in batch mode may no longer be so unrealistic.

If you would like to run fdisk in non-interactive batch mode on Linux, you can use one of the two methods.

Method One

The first method is to leverage the following shell snippet.

hdd="/dev/hda /dev/hdb /dev/hdc"
for i in $hdd;do
echo "n

"|fdisk $i;mkfs.ext3 $i;done 

Note that there are two blank lines between 1 and w lines. Given three hard drives (mapped to /dev/hda, /dev/hdb and /dev/hdc), this script creates for each hard drive a single primary partition, allocates all available space in the drive to the partition, and finally builds an EXT3-type file system on it. By tweaking the script, you should be able to create any number of (primary/logical) partitions for any number of disk drives in non-interactive fashion.

Method Two

The second method to automate disk partitioning is to use a command-line tool called sfdisk. This tool allows you to create/change partition tables according to the disk partitioning specification read from standard input. It also allows you to export the partition table specification of a device to a file, so that sfdisk can read the file back in to apply the same partitioning to a different device.

The basic usage of sfdisk for non-interactive disk partitioning is as follows.

To prepare a disk partitioning specification:

$ sudo sfdisk -d /dev/sda > my.layout

The exported disk layout information looks as follows.

$ cat my.layout
# partition table of /dev/sda
unit: sectors

/dev/sda1 : start=     2048, size=   497664, Id=83, bootable
/dev/sda2 : start=   501758, size=1953021954, Id= 5
/dev/sda3 : start=        0, size=        0, Id= 0
/dev/sda4 : start=        0, size=        0, Id= 0
/dev/sda5 : start=   501760, size=1953021952, Id=8e

To apply the same disk partitioning and layout to another device (e.g., /dev/sdb):

$ sudo sfdisk /dev/sdb < my.layout

Support Xmodulo

This website is made possible by minimal ads and your gracious donation via PayPal or credit card

Please note that this article is published by under a Creative Commons Attribution-ShareAlike 3.0 Unported License. If you would like to use the whole or any part of this article, you need to cite this web page at as the original source.

Xmodulo © 2021 ‒ AboutWrite for UsFeed ‒ Powered by DigitalOcean