Linux - how to format multiple file systems within one file?

It appears you can use the kpartx tools: http://robert.penz.name/73/kpartx-a-tool-for-mounting-partitions-within-an-image-file/

Kpartx can be used to set up device mappings for the partitions of any partitioned block device. It is part of the Linux multipath-tools. With kpartx -l imagefile you get an overview of the partitions in the image file and with kpartx -a imagefile the partitions will accessible via /dev/mapper/loop0pX (X is the number of the partition). You can mount it now with mount /dev/mapper/loop0pX /mnt/ -o loop,ro. After unmounting you can disconnect the mapper devices with kpartx -d imagefile.

You can do so by first mounting your partitions to /dev/loop? using losetup with the -o option to specify a suitable offset to your partition. The offset can be calculated based on the output of fdisk -l disk.img (start_sector * sector_size).

For example:

losetup -o32256 /dev/loop1 ./disk.img   # mount first partition

Once mounted, you can then proceed to format the partition using mkfs.*:

mkfs.vfat -F32 /dev/loop1

For more details and examples, see the following articles:

  • http://wiki.osdev.org/Loopback_Device#Mounting
  • http://web2.clarkson.edu/projects/itl/honeypot/ddtutorial.txt
  • http://wiki.eeeuser.com/howtocustomrestoreimage:pt2mkcustomimage