mkfs fails complaining that: "/dev/sdb is apparently in use by the system; will not make a filesystem here"

Solution 1:

Check your partitioning once again, but without specifying /dev/sda:

# fdisk -l

Then if you find in output something like /dev/md0, - it means that you have got sw array, and disk that you're trying to format contains metadata of that array.

In this case:

# umount /dev/md0
# mdadm --stop /dev/md0

Clear superblock of disk:

# mdadm --zero-superblock /dev/sdb

Remove array

# mdadm --remove /dev/md0

No you can work with your drive.

Solution 2:

/dev/sdb is in use because there are partitions on it that the OS is aware of. If you want to create a filesystem on it (a bad idea, because it is rarely done so will confuse administrators, and it will make it difficult to do any kind of splitting or resizing), first remove the existing partition with fdisk. If you want to create a filesystem on the sole partition /dev/sdb1 (this is what you should do, since there is no benefit to using the disk directly), then say what you mean: mkfs /dev/sdb1.

Solution 3:

You get this error message because /dev/sdb has a partition (i.e. /dev/sdb1) and the mkfs call would also overwrite all or parts of your partition table. In the worst case, your file system wouldn't be usable then. Or you 'just' loose a partition table you might still need. Since the partition device files and the actual on disk partition table should tell the same story, they are arguably 'in use' by the kernel.

Thus, the simple rule is: if you want to create your filesystem on the whole disk device then make sure all partitions are deleted before. For example:

# ls /dev/sdb*
/dev/sdb /dev/sdb1
# sfdisk --delete /dev/sdb
# sfdisk --list /dev/sdb
# ls /dev/sdb*
/dev/sdb

Usually, the partitioning tool takes care of notifying the kernel to update its partition device files. But sometimes (e.g. for loopback devices) it may be necessary to explicitly remove them (after the partition table is removed), e.g. via partx -dv mydev and/or kpartx -dv mydev.

Note that a previous kpartx -av mydev may create the partition devices as /dev/mapper/mydev* instead of /dev/mydev*. When they are present then mkfs complains in the same way.