1

I am trying to figure out a best way for running a while loop that read an input and the input can only be Y or N(upper or lower case), if something else has been entered (other than y or n) then run loop again.... also run loop again if its blank....below is what i came up with, but i am not that is not the best solution and does not seem to be working...

read ANS
while [[ $ANS = "" ]]; do
echo "This Cannot be Blank, Please enter answer again"
read ANS
done


while :
do
    echo "Enter Y for yes, N for no"
    read system
    case "${system}" in
        [yY]) export ANS=YES ;;
        [pP]) export ANS=NO ;;
    esac
done
max scalf
  • 329
  • 1
  • 8
  • 19
  • 1
    Four problems: 1. There's no `break` in the loop, so of course it's an infinite loop; 2. The case for no is `[pP]`? Typo? 3. I see no reason of exporting `ANS`. 4. What's the point of reading `ANS` only to overwrite it immediately without using it? – 4ae1e1 Nov 13 '15 at 05:16
  • You can test for `Yes` or `yes` as well with `[yY]*` (and the same for your `Pp` (fix to `Nn`)) – David C. Rankin Nov 13 '15 at 05:30
  • http://stackoverflow.com/a/23294659/874188 has a long and detailed discussion of options and pitfalls. It's for Python, but a lot of it will apply to Bash as well, or simply to programming in general. – tripleee Nov 13 '15 at 06:31

1 Answers1

1
 while :;do 
     read -p "Enter Y for yes, N for no: " request; 
     if [[ $request == [YynN] ]];then 
          break;
     fi;
done 
repzero
  • 8,254
  • 2
  • 18
  • 40