Scripting FDisk on Linux
scottalanmiller last edited by
Using BASH, we can easily automate the use of the fdisk utility in a script. We do this by echoing in the interactive session. It is far from ideal and doesn’t make for a very easy to read script, but it does the trick and that is what matters. Later we will look at performing the same task using parted, which is much cleaner. But fdisk is the traditional method and as long as your block device is under the 2TB limit, it works very well. Here is an example:
export device=/dev/sdb echo "n p 1 t 1 8e w" | fdisk $device
Because of the way that this echo command works, we have to format it in this way with the blank lines representing carriage returns. In this example we are create a new partition on an unused block device (/dev/sdb) and set it to be of the LVM type (8e) and write those changes to disk.
Originally posted in 2014 on my Linux blog here: http://web.archive.org/web/20140822211002/http://www.scottalanmiller.com/linux/2014/06/12/scripting-fdisk/