如果块设备已经格式化,则退出mkfs命令

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?

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.