fdisk - partition in single line

Trying to automate fdisk is possible, but it is not easy to maintain. As other answers note, either parted or sfdisk are designed to do what you want and are easier to automate.

parted

To create a partition in one line with parted:

parted -a optimal /dev/usb mkpart primary 0% 4096MB

as seen in this UNIX SE post. Each of the parts is pretty self-explanatory, but just in case here is how mkpart is defined:

mkpart [part-type fs-type name] start end

where things in square brackets are optional, but you probably want primary for your part-type, start at 0% and end at 4096MB or however large your USB stick is.


Erase everything, and create a single partition:

dev='/dev/sdb'
sudo umount "$dev"
printf "o\nn\np\n1\n\n\nw\n" | sudo fdisk "$dev"
sudo mkfs.ext4 "${dev}1"

See also: https://superuser.com/questions/332252/creating-and-formating-a-partition-using-a-bash-script


You probably need to use the parted command instead of fdisk.