Howto mkfs.ext4/create filesystem into image file?

Build task needs to create an OS image. Image is written to file, now need to add ext4 partition (or vfat or anything really) to the image.

Is there a way to do that? Mounting the image using loopback fails.

You need to create the filesystem before you can mount it. You can apply mkfs.ext4 directly to the file if you only need a filesystem image.

If you need to set up partitions within the image file you need to set up the loop device first using losetup and partition it. Note that to actually use partitions on a loop device the loop kernel module must be mounted with a suitably large max_part parameter.

Thank you for the quick answer. I already have the image file containing 3 partitions (boot, root, unallocated). I understand I need to mkfs.ext4 on the unallocated partition once the image file is mounted.

I’m still failing to do so on CI- any hint would be appreciated.

You can use command like this to set up the loop device:

sudo losetup --partscan /dev/loop0 disk.img

The --partscan parameters enables detection of partitions in the loop device, /dev/loop0 is the loop device you want to use. You might need to use another if you already use other loop devices, or use -f to automatically use a free one (but then you need to find which one).

The example command should give you additional devices for the partitions, named like /dev/loop0p1 (with 1 being the partition number here). You can work with those like with any disk partition, e.g. run mkfs.ext4 /dev/loop0p3.

1 Like