I'm making a bash script with a simple interactive menu that asks a yes or no question. I'm wondering if I can use a function to call itself and restart the prompt if the person writes random junk, is this possible?
Code:
Question () {
read -r -p "yes or no quesiotn [Y/N]"
Response
case Response in
Y|y)
#some code
;;
N|n)
#more code
;;
*)
ehco "im sorry i didnt catch that"
Question
;;
esac
}
Question
Instead of calling itself, make the function return appropriate exit codes, (a 1 for failed, a 0 for success), then have a do-nothing until loop do the work:
Question () {
read -r -p "Yes or no question [Y/N]?" Response
case "$Response" in
Y|y)
#some code
;;
N|n)
#more code
;;
*)
echo "I'm sorry I didn't catch that."
return 1
;;
esac
}
until Question ; do : ; done
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With