Search code examples
bashwhile-loopdo-while

How do I validate a while loop and repeat based on conditions


Please help! I am stuck. No matter what I do the script doesn't execute correctly. Any insight is appreciated.

#!/bin/bash

Name=""
User_Number="0"

read -rp "What is your name? " Name
read -rp "Enter a number between 1-10. " User_Number

while (($User_Number <= 0 && $User_Number >= 11)) 
do
echo "The number you entered is invalid. Please try again." 
read -rp "Enter a number between 1-10. " User_Number
continue
echo "Hey ${Name}, the number you entered is: ${User_Number}."
done

while ((1 >= $User_Number <= 10)) 
do
echo -e "\nHello ${Name}!"
echo "The number you entered is: ${User_Number}"
break
done

If the user's number is outside of 1-10 I want them to prompted to enter a new number. What's happening is when I test it out any numbers outside the range are treated as if they are in range.

I've tried rearranging the while loops to place one before the other to no avail. I've tried nesting them together through a while true if/then statement and that didn't work either. What am I overlooking? I've tried looking through other posts for help. Thanks. btw I'm new to bash scripting


Solution

  • You don't need the end of the script. My script uses -lt for less than and -gt for greater than, too. You should check out the correct syntax for this kind of comparison. Also, think about the use of && vs. || (you can't be both greater than and less than).

    #!/bin/bash
    
    Name=""
    User_Number="0"
    
    read -rp "What is your name? " Name
    
    read -rp "Enter a number between 1-10: " User_Number
    
    while [[ $User_Number -lt 1 || $User_Number -gt 10 ]]
    do
      echo "The number you entered is invalid. Please try again." 
      read -rp "Enter a number between 1-10: " User_Number
    done
    
    echo "Hey ${Name}, the number you entered is: ${User_Number}."