I've written a tiny function for asking questions intended for my POSIX shell scripts, where I often need user input.
The function takes 2+ arguments, where:
- Is a string containing the question.
- , 3., ... = arguments containing the right answers (case insensitive)
I also changed my style by a bit, no longer use ${var}
instead of just $var
.
The requirement was simple: Check for exactly the answers given. So, not matching yeahh
if given answer is yeah
.
I also included a maybe performance-wise quick test if the user answer is in the list of answers, so answering no
will not make the script iterate through all the answers and just dies at that check.
#!/bin/sh
set -u
confirmation ()
# $1 = a string containing the question
# $2,.. = arguments containing the right answers (case insensitive)
{
question=$1; shift
correct_answers=$*
correct_answers_combined=$( printf '%s' "$correct_answers" | sed 's/\( \)\{1,\}/\//g' )
printf '%b' "$question\\nPlease answer [ $correct_answers_combined ] to confirm (Not <Enter>): "
read -r user_answer
# this part is optional in hope it would speed up the whole process
printf '%s' "$correct_answers" | grep -i "$user_answer" > /dev/null 2>&1 ||
return 1
# this part iterates through the list of correct answers
# and compares each as the whole word (actually as the whole line) with the user answer
for single_correct_answer in $correct_answers; do
printf '%s' "$single_correct_answer" | grep -i -x "$user_answer" > /dev/null 2>&1 &&
return 0
done
# this might be omitted, needs verification, or testing
return 1
}
# EXAMPLE usage, can be anything, DO NOT review this part please
if confirmation 'Is dog your favorite pet?' y yes yep yeah
then
tput bold; tput setaf 2; echo 'TRUE: You just love dogs! :)'; tput sgr0
else
tput bold; tput setaf 1; echo 'FALSE: Dog hater, discontinuing! :('; tput sgr0
exit 1
fi
# do other stuff here in TRUE case
echo 'And here comes more fun...'
.*
? That's not in the list of accepted answers, yet it is accepted. \$\endgroup\$.*
, thanks \$\endgroup\$