Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Is there any way to create and format a partition using a bash script?

I think it can be done with fdisk but I don't know how to feed commands from the bash script into the fdisk shell then exit the fdisk shell.

I'm wanting to create a partition then format it to ntfs from within bash.

share|improve this question

6 Answers 6

up vote 12 down vote accepted

You can do it with just a couple of commands, use intros \n instead of multiple echos.

echo -e "o\nn\np\n1\n\n\nw" | fdisk /dev/sda
share|improve this answer
    
This is more terse than the others, but unfortunately seems to only work with bash. –  bk138 Feb 9 at 18:34
    
It's working with ash/busybox too. –  kikeenrique Feb 10 at 8:59
    
There are, however, problems with dash :-/ –  bk138 Feb 11 at 15:01

fdisk reads from stdin so you just need to feed it the appropriate commands. For example, the following clears the partition table, if there is one, and makes a new one that has a single parititon that is the; entire disk:

(echo o; echo n; echo p; echo 1; echo ; echo; echo w) | sudo fdisk

I recommend you do the task you want, recording what you type so you can reproduce it.

share|improve this answer

You can script fdisk.

(echo n; echo p; echo 1; echo 1; echo 200; echo w) | fdisk /dev/sdc

That creates a 200 MB partition on /dev/sdc

share|improve this answer

Check out: Parition with sfdisk. All you need to do is make a file, in a certain format that sfdisk will read, then read it into sfdisk.

share|improve this answer
    
sfdisk is too hard :< –  Felipe Alvarez Jun 17 at 23:37

I don't think you can create a partition with fdisk without interacting. You'll want to use parted or sfdisk

share|improve this answer

Piping commands to fdisk works well as explained by other people, but this way a bit more elegant and readable:

fdisk /dev/sdc <<EOF
n
p
1


w
EOF

Piping from a (temporary) file also works:

fdisk /dev/sdc < /tmp/fdisk.cmds
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.