Problems with kpartx in a script

I am trying to run the rpi-image-creator script (see, and encounter some trouble with the kpartx use. The trouble seems to occur in the ‘_open_image’ function. Here’s the code:

function _open_image {
   echo "Loop-back mounting" temp/*.img
   kpartx="$(kpartx -av temp/*.img)" || die "Could not setup loop-back access to $RASPBIAN_ARCHIVE_FILE:$NL$kpartx"
   read img_boot_dev img_root_dev <<<$(grep -o 'loop.p.' <<<"$kpartx")
   test "$img_boot_dev" -a "$img_root_dev" || die "Could not extract boot and root loop device from kpartx output:$NL$kpartx"
   mkdir -p mnt/img_root
   mount -t ext4 $img_root_dev mnt/img_root || die "Could not mount $img_root_dev mnt/img_root"
   mkdir -p mnt/img_root/boot || die "Could not mkdir mnt/img_root/boot"
   mount -t vfat $img_boot_dev mnt/img_root/boot || die "Could not mount $img_boot_dev mnt/img_root/boot"
   cp -a "$(type -p qemu-arm-static)" mnt/img_root/usr/bin/ || die "Could not copy qemu-arm-static"
   echo "Raspbian Image Details:"
   df -h mnt/img_root/boot mnt/img_root | sed -e "s#$(pwd)/##"

Running the script (in my case with –chroot) I obtain the following error:

    mount: special device /dev/mapper/loop0p2 does not exist
    ERROR: Could not mount /dev/mapper/loop0p2 mnt/img_root

I’ve added a monitoring line right before the mount command, listing the contents of /dev/mapper, and it actually shows that ‘loop0p1’ and ‘loop0p2’ do not exist, implying that something must have gone wrong when calling kpartx earlier. At the same time, however, the variables seem to get assigned the correct names of the loop devices.

Strangely enough, running ‘kpartx -a temp/*.img’ manually right before calling the script seems to work. And after the script exits with the error above, the loop devices suddenly exist where they should be.

Assuming that the script does not have a bug, I guess there must be something odd going on in my system. What’s going wrong and how do I fix this?

(Running this on a Debian Jessie with kernel 3.16.0-4-amd64, kpartx version 0.5.0-6+deb8u1, bash 4.3.30(1)-release with an empty .bashrc)


I also ran into a similar problem in a backup-script when I tried to mount a partition from a mapping created using kpartx. After a trying sync (failed) and sleep 0.5 (worked) I had another look at the (debian) kpartx manpage which offers the -s-switch. This does:

-s     Sync mode. Don't return until the partitions are created

now, running kpartx -avs /dev/hostVolumegroup/logicalVolumeSnapshot and mounting a partition afterwards works flawlessly and I don’t need workarounds.

Leave a Reply

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