Mounting Images with kpartx
kpartx
Recently I wanted to mount a partition from an image. Not so easy, as Linux usually does not look at the MSB from loop mounted devices. However loop has the offset-feature, such that you can mount a partition. And there is a userspace tool to calculate that.
Warning! The description below has a bug, in that it does not mount a partition correctly. The partition start is correct, but the length is the entire image. So if you mount it r/w and use tools like resizee2fs you will corrupt partitions behind the mounted partiton!
Sadly kpartx was not designed as a shell tool. It is a bit complex to use it from shell, as it outputs human readable text which must be parsed. And it is lacking an option to fix that.
Below method uses a nonstandard way to access the data. As long as kpartx does not change it's output, everything should work. But it is not recommended. A recommended way is unknown so far.
# This function mounts an image using kpartx and returns the list of mounted partitions.
map()
{
kpartx -va "$1" | awk '{print $3}'
}
# unmount an image
umap()
{
kpartx -d "$1"
}
IMG=img
parts="`map "$IMG"`"
for part in $parts
do
: do something with /dev/mapper/$part
done
umap "$IMG"