-1

Restricting user from trying multiple invalid attempt in shell scripting. I wrote the below script but somehow it's not getting me desire output. I have shared the script and script output both. Kindly help. Here I wanted script to terminate if user tried more than 3 times.

While true
do
echo -n "Enter yes or no"
read opt
case $opt in
yes) break ;;
no) break ;;
*) echo "Invalid input"
while [[ $err -le 3 ]]
do
 If [[ $err -le 3 ]]
then
echo "err: $err"
((err++))
break
else
echo "Max limit crossed"
exit 1
fi
done
;;
esac
done
kvantour
  • 25,269
  • 4
  • 47
  • 72
Rimo1988
  • 21
  • 3
  • 2
    Please take a [tour]. – KamilCuk Dec 04 '20 at 10:22
  • I recommend you to use `select` instead of a loop. This way you don't have the problem with wrong answers. Have a look at the second option in [this answer](https://stackoverflow.com/a/226724/8344060) – kvantour Dec 04 '20 at 10:30
  • Does this answer your question? [How do I prompt for Yes/No/Cancel input in a Linux shell script?](https://stackoverflow.com/questions/226703/how-do-i-prompt-for-yes-no-cancel-input-in-a-linux-shell-script) – kvantour Dec 04 '20 at 10:30
  • If you think a answer was helpful mark it as accepted, button below up-dwon voting – Aalexander Feb 14 '21 at 16:10

2 Answers2

1

This was a nice question and I had a lot of fun solving it. I have to mention that I'm new to shell programming.

  n=0
  until [ $n -ge 3 ] 
  do 
  read line
    if [ "$line" = "XYZ" ]; then 
        echo "Accepted" 
        break
    else
        n=$[$n+1]
        echo " trying " $n "times "   
    fi;
  done

This article helped me a lot to solve it.

Aalexander
  • 4,987
  • 3
  • 11
  • 34
0

Try:

#!/bin/bash
ANSWER=
max=3
while true; do
     echo "Enter yes or no:"
     read -r ANSWER
     [[ $ANSWER == "yes" || $ANSWER == "no" ]] && break
     echo Invalid Input
     ANSWER=
     ((--max))
     [[ $max -le 0 ]] && { echo "Max limit crossed"; exit 1; }
done
Jay
  • 66
  • 6
  • I found this partially opposite of what Alex suggested above. This also should serve the purpose. Thanks – Rimo1988 Dec 12 '20 at 05:18