Ubuntu – Automated Shell script to run fdisk command with user input

bashcommand linefdiskpartitioningscripts

I'd like to create a bash shell script that can run commands and provide input as if I was typing it on the terminal.

I have written bash shell scripts before and understand how to but I'm a bit confused on how it 'interfaces'.

Currently, I'm required to run fdisk and other terminal commands and then go through their option panel providing a set/specified input. It is taking too long and since it is constant, I was wondering then how I would go about it.

I get that a shell script is like if you were to type that command into the terminal. Thus, can I just literally write a script that says something like:

sudo fdisk /dev/sda








As an example where the single string entries are what I type on my keyboard as fdisk waits for commands. This doesn't seem valid but it may be.

Also, something I have to do after those commands run is unplug the drive and then continue running it. Am I able to implement that into my program to wait for me to unplug, and replug and then continue running automated script?

I appreciate all the help.

Best Answer

I wrote myself a little script using the fdisk command, based on what I know plus bits of code found online, which does something very similar, namely, interactively format a drive into one or more partitions, asking if this is the correct drive, waiting for a set time, or input from the user, warning it is about to erase it, etc. One thing it cannot do, in its current form, is resume running after it's stopped for any reason, from getting the input "No, don't format!" from the user, or simply an error. Once it stops, it has to be run again.

Note: $(echo $Output_Device) is a shell variable, and can be replaced with e.g. sdb or any similar name for a disk device. The actual fdisk command(s) I cobbled together are:

Formats the disk into two partitions, 1 of size 64Mb, and 2 the rest of the disk:

(echo o; echo n; echo p; echo 1; echo ""; echo +64M; echo n; echo p; echo 2; echo ""; echo ""; echo w; echo q) | fdisk /dev/$(echo $Output_Device)

Then, actually formats the partitions, 1 as FAT, 2 as ext3:

mkfs.vfat -n BOOT /dev/$(echo $Output_Device)1

mkfs.ext3 -L root /dev/$(echo $Output_Device)2

I can post the whole script, but it is messy, and I like to keep commands in it even when they're commented out, for my own reference.

The more general case, how to make it resume, I may or may not be able to do, haven't tried. Likewise, this works with fdisk, but other commands may/will need a different syntax.