To make a partition table, you can use your common tools directly on the file instead of the device. Most standard tools should support this usage, like
parted is great to be integrated in a script as it can take the commands as argument.
parted -s testing.img mklabel gpt
parted -s -a none testing.img mkpart ESP fat32 0 4M
parted -s -a none testing.img mkpart linux ext4 4M 10M
File system creation
I don't have a clean solution to mount or create a file system in a virtual partition. The right thing to do would probably be to have a
fuse (Filesystem in Userspace) driver for partition tables. But I haven't found one at the moment.
mke2fs can take a
-E offset=1234 option to build an
ext4 file system at an arbitrary offset within the file. You can give it the offset of your partition. However, be sure to give it the size of the file system as well since the default behavior seems buggy and write a file system with the size of the virtual disk by default, extending the file if needed.
mke2fs -E offset=4000256 testing.img 6316k
Unfortunately, not all the
mkfs have such an option.
mkfs.vfat doesn't. So another solution can be to create a separate file of the size of the partition, use
mkfs on it and then use
dd to copy the content into the full virtual disk.
dd if=testing.img of=testing.fat32.img bs=512 skip=34 count=7779
mkfs -t vfat testing.fat32.img
dd if=testing.fat32.img of=testing.img bs=512 seek=34 count=7779 conv=notrunc
Not the cleanest or fastest solution, but it works, it is quite generic and it doesn't require root privileges. The conversion option
sparse can also be used to speed things up a bit by not writing longs sequences of zeros.
Mounting file systems
You can mount a file system in a partiton with the help of
fuse provided it has a support for your file system. There is a standard support for
ext file systems under the name
fuse-ext2 and one for
FAT under the name
fusefat. They unfortunately don't take an
offset option at the moment. So I guess you're bound to either using
mount or the same
dd trick as earlier.
The standard method with
kpartx, (or the
-o offset option of
mount) require root privileges. The
dd solution is slow, complex and error-prompt.