Mounting IMG files under Linux

Posted by

Update: There are errors with the below for which I did not find a solution yet. I did find a different approach which you can read in: Mounting IMG files under Linux [Updated]

Next to working on my MacBook Pro, I work most of the time on my new PC with Ubuntu 18.04 LTS. Still working with Raspberry Pi’s gives me the need to work with images to manipulate to my needs before I write them to the SD cards. This article assumes working on the Raspbian image that contains two partitions.

Create the mount points for the two partitions in the image:

mkdir -p /media/img1
mkdir -p /media/img2

IMG files are a full representation of a filesystem. Therefore it is needed to determine the starting point for the mount in the IMG file:

fdisk -l /path/to/image-file

Output:

sudo fdisk -l 2019-09-26-raspbian-buster-lite.img

Disk 2019-09-26-raspbian-buster-lite.img: 2.1 GiB, 2248146944 bytes, 4390912 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: 0x6c586e13

Device                                   Boot   Start   End Sectors Size Id Type

2019-09-26-raspbian-buster-lite-ssh.img1 8192   532479  524288      256M c  W95 FAT32 (LBA)
2019-09-26-raspbian-buster-lite-ssh.img2 532480 4390911 3858432     1.9G 83 Linux

In this example the boot partition is the first and starts at block 8192 and the sector size is 512. The offset is 8192 x 512 = 4194304  

Mount command looks like:

sudo mount -o loop,offset=4194304 /path/to/image-file /media/img1

A little more sophisticated version that will calculate the offset in one go:

  • Mounting the first partition:
sudo mount -t auto -o loop,offset=$((8192*512)) /path/to/image-file /media/img1
  • Mounting the second partition:
sudo mount -t auto -o loop,offset=$((532480*512)) /path/to/image-file /media/img2

When finished making changes to the file, un-mount the image:

sudo umount /media/img1 && sudo umount /media/img2

Leave a Reply

Your email address will not be published. Required fields are marked *