Lars
Lars

Reputation: 776

until loop with if statements

I am stuck on a part and i don't understand why, let me paste my code:

    local correctId=false
    echo $ticketMessage
    read deviceId

     until [[ $deviceId =~ [0-9]+ && correctId = true ]]; do

      if [ ! -e $baseDevicesPath"/$deviceId" ]; then
       echo $deviceError
       correctId=false
      else
       correctId=true
      fi

     if [[ ! $deviceId =~ [0-9]+ ]]; then
       echo $ticketMessage
     fi

      read deviceId
     done

    echo "I DONT COME HERE?"

if both deviceId and correctId are true, it should exit the until loop and go further? but it doesn't, any idea what i do wrong here?

Upvotes: 1

Views: 55

Answers (3)

Didko
Didko

Reputation: 11

here is a bit more readable solution

function findDevice {
echo $ticketMessage;
read deviceId;

while true; do
    local errorMessage;
    if [[ $deviceId =~ [0-9]+ ]]; then
        if [ -e $baseDevicesPath"/$deviceId" ]; then
            #valid input, breaking the loop
            break;              
        fi
        errorMessage=$deviceError;
    else
        errorMessage=$ticketMessage;
    fi
    echo $errorMessage;
    read deviceId;
done
}

Upvotes: 0

Walter A
Walter A

Reputation: 20012

Change correctId into $correctId (of ${correctId}). I would add double quotes:

local correctId="false"
echo ${ticketMessage}
read deviceId

until [[ $deviceId =~ [0-9]+ && "${correctId}" = "true" ]]; do

  if [ ! -e "${baseDevicesPath}/${deviceId}" ]; then
   echo ${deviceError}
   correctId="false"
  else
   correctId="true"
  fi

 if [[ ! "${deviceId}" =~ [0-9]+ ]]; then
   echo ${ticketMessage}
 fi

  read deviceId
 done

echo "Do you come here?"

Upvotes: 0

hexerei software
hexerei software

Reputation: 3160

You just have a simple typo. you are missing the $ in front of correctID in your condition:

local correctId=false
echo $ticketMessage
read deviceId

 until [[ $deviceId =~ [0-9]+ && $correctId = true ]]; do

  if [ ! -e $baseDevicesPath"/$deviceId" ]; then
   echo $deviceError
   correctId=false
  else
   correctId=true
  fi

 if [[ ! $deviceId =~ [0-9]+ ]]; then
   echo $ticketMessage
 fi

  read deviceId
 done

echo "NOW YOU WILL END HERE"

Upvotes: 1

Related Questions