Working with Image Files

When working with virtual machine disk images, it is not uncommon for them to contain partitions, and not just a single filesystem which starts at block 0.

There are two basic ways to mount a filesystem contained within the former type of images:

  1. Use fdisk -l to get the image's partition information
  2. Calculate the byte offset of the partition of interest (multiplying the starting sector reported by fdisk by the sector size, usually 512)
  3. Use mount -o loop,offset=${STARTING_OFFSET} -t ${FS_TYPE} to mount
# fdisk -l 2022-04-04-raspios-bullseye-armhf-lite.img
Disk 2022-04-04-raspios-bullseye-armhf-lite.img: 1,9 GiB, 2017460224 bytes, 3940352 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x7d5a2870

Device                                      Boot  Start     End Sectors  Size Id Type
2022-04-04-raspios-bullseye-armhf-lite.img1        8192  532479  524288  256M  c W95 FAT32 (LBA)
2022-04-04-raspios-bullseye-armhf-lite.img2      532480 3940351 3407872  1,6G 83 Linux
# mount -o loop,offset=$(( 532480 * 512)) 2022-04-04-raspios-bullseye-armhf-lite.img /mnt
# losetup
/dev/loop0         0 272629760         1  0 /tmp/2022-04-04-raspios-bullseye-armhf-lite.img   0     512

If your system has udiskctl installed, all of the contained filesystems can be mounted automatically using the udiskctl command:

$ udisksctl loop-setup --file 2022-04-04-raspios-bullseye-armhf-lite.img 
Mapped file 2022-04-04-raspios-bullseye-armhf-lite.img as /dev/loop8.
$ mount
/dev/loop0p1 on /media/username/boot type vfat (rw,nosuid,nodev,relatime,uid=1000,gid=1000,uhelper=udisks2, ...)
/dev/loop0p2 on /media/username/rootfs type ext4 (rw,nosuid,nodev,relatime,uhelper=udisks2)
  • Last modified: 2022-04-18 10:41
  • by Peter