0

I'm writing a utility which needs to run mkfs to format a block device.

I use go's exec package to run the correct mkfs command for each file system type, for example in the case of ext2:

err := exec.CommandContext(ctx, "mkfs.ext2", "-F", path).Run()

Unfortunately if the block device is already formatted mkfs will ask for confirmation (and hang). This means that I'm forced to pass the dangerous -F flag to skip this check, loosing data if the device was already formatted.

I can't add a timeout to the context, because formatting might take a while for other reasons than this confirmation.

I can't find a mkfs flag which makes it return an error instead of a confirmation check if the block device is already formatted.

I would prefer not to rely on parsing the mkfs command's output to see if it's asking for the confirmation check since that would make it break if the mkfs output changes.

Is there a way to abort the command with the correct error message if the block device is already formatted instead of hanging on this confirmation check?

cachemoi
  • 343
  • 2
  • 13
  • hmm how about using a pipe? You can add the answer to the prompt (continue/cancel?) and then execute the command: https://stackoverflow.com/questions/10781516/how-to-pipe-several-commands-in-go I mean, you should try to reproduce the command: `echo Y | mkfs.ext2` or similar – kabanek Jun 10 '19 at 11:29
  • That would not be ideal because I'd be sending "n" whatever the prompt is. Dangerous if the prompt is something like "do you want to keep your data" or if mkfs changes in any way. – cachemoi Jun 10 '19 at 11:38
  • I don't think that they'll do some huge backward incompatible change but if you want to make sure you have to or parse the output or check the version before using it. – kabanek Jun 10 '19 at 12:32

1 Answers1

0

It turns out that if we run the command without a terminal (tty), the -F option is assumed and the device is formatted regardless of whether or not the target device already has a file system.

this occurs with mkfs.ext2, mkfs.ext3 and mkfs.ext4

this is actually legacy behavior as indicated here

mkfs.xfs and mkfs.btrfs behave correctly and error if the block device is already formatted.

I'm posting this as an answer since I think this means that there's no actual solution... running mkfs.ext2 outside the terminal will always delete data if there's already some on the device.

cachemoi
  • 343
  • 2
  • 13