paladin
paladin

Reputation: 790

mounting multiple partitions from a disk image file

I'm trying to write a small bash script which shall mount all partitions from a given disk image file. I know that this works, because I did this already in the very past, but I can't remember anymore. Maybe I was using somehow /dev/mapper but I can't remember. I'm using for the sizelimit parameter the actual size of the partition and not the absolute sector end of the partition.

Sorry for my bad English.

#!/bin/bash

source=$1
destination=$2

if !(fdisk $source -l); then
    exit 1
fi

echo ""

partdata=$(fdisk $source -l|grep $source|tail -n +2)

offset=0
sizelimit=0

while [ "$partdata" != "" ]; do
    read -ra ARRAY <<< "$partdata"

    echo "ARRAY: ${ARRAY[0]} ${ARRAY[1]} ${ARRAY[2]} ${ARRAY[3]}" #echo for debugging

    mkdir $destination"/"${ARRAY[0]}
    ((offset=512*${ARRAY[1]}))
    ((sizelimit=512*${ARRAY[3]}))

    echo "#mount -v -o ro,loop,offset=$offset,sizelimit=$sizelimit -t auto $source $destination/${ARRAY[0]}" #echo for debugging

    mount -v -o ro,loop,offset=$offset,sizelimit=$sizelimit -t auto $source $destination"/"${ARRAY[0]}

    echo ""

    partdata=$(echo "$partdata"|tail -n +2)
done

exit 0

EDIT: translated error-message:

mount: /mnt/raspi_qr_prototype_test_sample.img2: Wrong file system type, invalid options, the superblock of /dev/loop1 is corrupted, missing encoding page, or some other error.

Upvotes: 1

Views: 1731

Answers (1)

KamilCuk
KamilCuk

Reputation: 141768

Consider a different approach that doesn't need to take some offset calculations. Let's first create a sample file with DOS partition table:

truncate -s 20M file.img
printf "%s\n" o n p 1 '' +10M n p 2 '' '' p w | fdisk ./file.img

then you can mount the whole image as a loop device:

loopf=$(sudo losetup --find --partscan --show ./file.img)

--find will make losetup find the first free loop device and output it, like /dev/loop0.

Then --partscan will work like partprobe, it will read the image and detect the partition and create appropriate files representing them with offset locations as in the partitioning table:

$ ls /dev/loop0*
/dev/loop0  /dev/loop0p1  /dev/loop0p2

After that, you can use p1 and p2 as normal partitions, as you would normally:

for i in "$loopf"p*; do
    sudo mount "$i"  "somwheere/$(basename "$i")"
done

After you're done, umount all directories and disconnect loop device with:

sudo losetup -d "$loopf"

Upvotes: 2

Related Questions