Sample Header Ad - 728x90

Not working break in for loop in bash script for mounting a VHD

2 votes
1 answer
166 views
I'm not an experienced programmer. So maybe it's obvious for you why the break command in this script does not terminate the loop, but I can't see what is causing the problem. I want to use the script to mount a VHD file to the first empty NBD "slot" (which is assumed when it's size is zero, I took this idea from another thread on this site).
function vhdmount() {
 workfile="$1"
 if test -e "$workfile"
 then
  workname=${workfile##*'/'}
  echo "$(tput setaf 3)*** ${workfile}: ***$(tput setaf 7)"
  for (( i=0; i<16; i++ ))
  do (
   if test -e /sys/class/block/nbd${i}/size
   then
    usedornot=$( cat /sys/class/block/nbd${i}/size )
    if (( "$usedornot" == 0 ))
    then
     firstfree=$i
     break
    fi
   else
    firstfree=$i
    break
   fi
  ); done
  sudo modprobe nbd
  sudo qemu-nbd -c /dev/nbd${firstfree} "$workfile"
  sudo mkdir "/media/myusername/${workname//.vhd/.nbd${firstfree}}/"
  sudo mount /dev/nbd${firstfree}p1 "/media/myusername/${workname//.vhd/.nbd${firstfree}}/"
  echo "$(tput setaf 3)    successfully mounted.$(tput setaf 7)"
 fi
}

vhdmount "$1"
Maybe there are other errors as well. I'm always terminating the shell when it asks for the password, because I can tell from the 16 messages telling me that a break command is only useful in a for loop that the break command did not work. By the way, what a useless error message is that?!
Asked by Shakesbeer (123 rep)
Jun 24, 2024, 10:03 AM
Last activity: Jun 24, 2024, 10:32 AM