Home > Software engineering >  How to break while loop after 5 attempts?
How to break while loop after 5 attempts?

Time:03-11

How to keep track of how many guesses the user makes and print a message that tells them they lose? Exit after 5 guesses.

num=$(( $RANDOM % 100   1 ))

while [ "$input" -ne "$num" ]; do
if [ "$input" -gt "$num" ]; then
echo "The number is too high."
read input
elif [ "$input" -lt "$num" ]; then
echo "The number is too low."
read input
fi
done
echo "Great, you picked the right number."

CodePudding user response:

Would you please try the following:

#!/bin/bash

num=$(( $RANDOM % 100   1 ))

for (( i = 0; i < 5; i   )); do
    read -p "Enter a number: " input
    if (( input == num )); then
        echo "Great, you picked the right number."
        break
    elif (( input > num )); then
        echo "The number is too high."
    elif (( input < num )); then
        echo "The number is too low."
    fi
done

BTW I tested the script by modifying the random number generator to $RANDOM % 10 1 but still not easy :).

  •  Tags:  
  • bash
  • Related