Skip to content

Instantly share code, notes, and snippets.

@zvodd
Created November 17, 2014 15:12
Show Gist options
  • Select an option

  • Save zvodd/03e2c9d4f5d8bea61925 to your computer and use it in GitHub Desktop.

Select an option

Save zvodd/03e2c9d4f5d8bea61925 to your computer and use it in GitHub Desktop.
Bash Script: Recursive YES/NO user input with parameter for maximum retries.
#!/bin/bash
yesnochoose () {
# $1 is the maximum number of retries
max=$( [ "$1" -eq "$1" ] 2>/dev/null && echo $1 || echo 5 )
# $2 is the retry count and should not be set when called outside of recursion.
count=$( [ "$2" -eq "$2" ] 2>/dev/null && echo $2 || echo 0 )
read uchoose
uchoose=$(echo $uchoose | sed -e 's/\(.*\)/\U\1/' -e 's/ //g')
case "$uchoose" in
"YES"|"YE"|"Y")
return 0
;;
"NO"|"N")
return 1
;;
*)
count=$(expr $count + 1)
if [ "$count" -ge "$max" ]; then
return 2
else
>&2 echo "Please type 'yes' or 'no'"
return $(yesnochoose "$max" "$count")
fi
;;
esac
}
#example usage:
echo "Type yes or no"
yesnochoose
case "$?" in
0)
echo "You selected yes"
;;
1)
echo "You selected no"
;;
2)
echo "Maximum attempts exceeded"
;;
esac
echo "Type yes or no, you only get one shot."
yesnochoose 1
case "$?" in
0)
echo "You selected yes"
;;
1)
echo "You selected no"
;;
2)
echo "Maximum attempts exceeded"
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment