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-typefs-typename] startend
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.
The sfdisk man page is a little confusing, here's some specific examples of how to automate partition setup with sfdisk. One example is you can save the partition info from one drive via sfdisk -l and then dump that directly on to a new drive.
-n, --new=partnum:start:end
Create a new partition. You enter a partition number, starting sector, and an ending sector. Both start and
end sectors can be specified in absolute terms as sector numbers or as positions measured in kibibytes (K),
mebibytes (M), gibibytes (G), tebibytes (T), or pebibytes (P); for instance, 40M specifies a position 40MiB
from the start of the disk. You can specify locations relative to the start or end of the specified default
range by preceding the number by a '+' or '-' symbol, as in +2G to specify a point 2GiB after the default
start sector, or -200M to specify a point 200MiB before the last available sector. A start or end value of 0
specifies the default value, which is the start of the largest available block for the start sector and the
end of the same block for the end sector. A partnum value of 0 causes the program to use the first available
partition number.
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
: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:where things in square brackets are optional, but you probably want
primary
for your part-type, start at0%
and end at4096MB
or however large your USB stick is.Erase everything, and create a single partition:
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.
sfdisk
also has a non-interactive mode that reads in partition information from stdin.parted
is more flexible, though.Use sfdisk instead.
The sfdisk man page is a little confusing, here's some specific examples of how to automate partition setup with sfdisk. One example is you can save the partition info from one drive via
sfdisk -l
and then dump that directly on to a new drive.For GPT tables you can use sgdisk: