1

I'm trying to make this BASH script require the user to input a value between 1 through 4 to choose a ninja turtle in the case statement. Any other value will cause $COUNTER to remain equal to 0 therefore requiring the case statement to execute again. However, I end up in an infinite loop if I enter any value other than 1 through 4.

1st - How do I nest a case statement inside a while loop?

2nd - How do I make this script require the user input a value between 1 - 4

#!/bin/bash                                    

echo "What is your favorite Ninja Trutle?"     

echo "1 - Raphael."                            
echo "2 - Leonardo."                           
echo "3 - Michelangelo"                        
echo "4 - Donatello"                           

read TURTLE;                                   
COUNTER=0;                                     

while [ $COUNTER -eq 0 ]                       
do                                             
   $COUNTER=$(( $COUNTER + 1 ))                

   case $TURTLE in                             
      1) echo "Raphael is cool, but rude.";;   
      2) echo "Leonardo leads.";;              
      3) echo "Michelangelo is a party dude.";;
      4) echo "Donatello does machines.";;     
      *) echo "Did you even watch the show?"   
         $COUNTER=0                            
         ;;                                    
   esac                                        
done

Thanks for any help provided.

  • Moreover, you want to have the read part within the while loop, otherwise the script realizes the input is wrong, but it doesn't ask the user again for a new value. – pfnuesel May 27 '17 at 6:37
  • The assign must be COUNTER=0 (w/o dollar sign) – Romeo Ninov May 27 '17 at 6:39
2

The error is in the lines in which you increment COUNTER. The $ symbol is used when you want to dereference the name of a variable to get its value. It's not used when you assign a value to the variable. Those lines should read:

COUNTER=$(( $COUNTER + 1 ))

and

COUNTER=0

Also, since the case command is inside the while loop, I assume you want to prompt the user again if he enters an invalid value. If that's so, you should put the read statement inside the while loop as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.