fdisk - partition in single line
Solution 1:
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.
Solution 2:
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
Solution 3:
You probably need to use the parted command instead of fdisk.
Solution 4:
sfdisk
also has a non-interactive mode that reads in partition information from stdin. parted
is more flexible, though.
Solution 5:
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.