Make it more robust be looking for an unused loopback device
#!/bin/bash
+if [ "$TERM" == "screen" ]; then
+ echo "Running as a background job in screen, won't use any sudo commands"
+ echo "exiting..."
+ exit 0
+fi
+
if [ ! -f "$1" ]; then
echo call with $0 smcardimage
exit 1
@@ -11,12 +17,37 @@ if [ "$KPARTX" == "" ]; then
exit
fi
-sudo losetup /dev/loop99 $1
-sudo kpartx -a /dev/loop99
+# find unused loop device
+free_loop_device() {
+ for i in 0 1 2 3 4 5 6 7 8 9; do
+ for j in 0 1 2 3 4 5 6 7 8 9 0; do
+ loid=$i$j
+ loid=`echo $loid | sed 's/^0*//'`
+ if [ "$loid" == "" ]; then
+ continue
+ fi
+ if [ ! -e /dev/loop$loid ]; then
+ LOOPDEVICE=loop$loid
+ return
+ fi
+ done
+ done
+}
+
+free_loop_device
+if [ "$LOOPDEVICE" == "" ]; then
+ echo "couldn't find usuable loopback device name, existing..."
+ exit 1
+else
+ echo "using $LOOPDEVICE"
+fi
+
+sudo losetup /dev/${LOOPDEVICE} $1
+sudo kpartx -a /dev/${LOOPDEVICE}
ls -l /dev/mapper
-sudo dosfsck -a /dev/mapper/loop99p1
-sudo fsck.ext4 -v -f /dev/mapper/loop99p2
-sudo kpartx -d /dev/loop99
-sudo losetup -d /dev/loop99
+sudo dosfsck -a /dev/mapper/${LOOPDEVICE}p1
+sudo fsck.ext4 -v -f /dev/mapper/${LOOPDEVICE}p2
+sudo kpartx -d /dev/${LOOPDEVICE}
+sudo losetup -d /dev/${LOOPDEVICE}
