0

I'm using this to wipe a USB flash drive and recreate a FAT filesystem:

dd if=/dev/zero of=/dev/sdb bs=1M    #I don't need more advanced wiping
fdisk /dev/sdb
(a few keystrokes to select partition type, etc.)
mkfs.fat /dev/sdb1

The fact that I have to manually do a few keystrokes is annoying. How could I do all of this in one step, without any intervention? Something like:

dd if=/dev/zero of=/dev/sdb bs=1M && ??? &&& mkfs.fat /dev/sdb1
Basj
  • 2,351
  • 9
  • 37
  • 70

2 Answers2

2

Here-document syntax allows you to use fdisk non-interactively:

fdisk /dev/sdb <<EOF
n
p



t
b
p
q
EOF

Because this is just an example, I used p and q so no changes are written. Use w after your verified sequence.

Note a blank line corresponds to sole Enter. The point is you can pass your keystrokes this way.

Alternatively you can write those lines (between two EOF-s) to a file, say fdisk.commands, and then:

fdisk /dev/sdb < fdisk.commands

Or without a file (from a comment, thank you Rastapopoulos):

fdisk /dev/sdb <<< $'n\np\n\n\n\nt\nb\np\nq'

Another way:

printf '%s\n' "n" "p" "" "" "" "t" "b" "p" "q" | fdisk /dev/sdb

There's also sfdisk. You may find its syntax more suitable for you.

Kamil Maciorowski
  • 19,242
  • 1
  • 50
  • 94
0

Based on @KamilMaciorowski's answer (full credit to him), here is what I finally use:

sudo dd if=/dev/zero of=/dev/sdb bs=1M && sudo fdisk /dev/sdb <<< $'n\np\n\n\n\nt\nb\np\nw\n' && sudo mkfs.fat /dev/sdb1
Basj
  • 2,351
  • 9
  • 37
  • 70