1

I am writing a script called pickanumber.sh. I was setting up the script so I will ask the user to pick a number. If the number that they type is not "8" than the script will continue running. I can't make the script keep running when the user picks a number other than "8". Should I use for loop or while loop? Here is the script that I have so far.

rand_num=0
let "rand_num = $RANDOM % 10 + 1"
echo $rand_num
echo -n "pick a number from 1 - 10! "
read pickanumber
if [ "$pickanumber" = "8" ]; then
   echo "GOOD JOB"
else
   read $pickanumber
fi          
0

2 Answers 2

1

Use while loop, or until.

until [ "$pickanumber" = "8" ]; do
    echo -n "pick a number from 1 - 10! "
    read pickanumber
done
echo "GOOD JOB"
1
  • thank you @ipor Siecer. it works. when i used until command. but when i try using while loop, it takes every number as a correct number. can you tell me how to use while loop in this case ? thank you. Commented Mar 14, 2017 at 5:55
0
#!/bin/bash
let "rand_num = $RANDOM % 10 +1"
pickanumber=0
printf "Pick a number on this range [1-10]:"
read pickanumber

while [ true ]; do
 if [ $pickanumber -eq $rand_num ];then
  echo "Good Job!"
  exit
 else
  printf "Wrong, try again?"
  read pickanumber
 fi
done
0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.