Browse Source

fixed ask_yn maybe

main
deicidus 1 year ago
parent
commit
b162f452cc
  1. 53
      spells/cantrips/ask_yn

53
spells/cantrips/ask_yn

@ -1,34 +1,31 @@
#!/bin/sh #!/bin/bash
ask_yn() { question=$1
default=${2:-"y"} default_answer=$2
default=$(printf "%s" "$default" | tr '[:upper:]' '[:lower:]')
# Set prompt string # Capitalize the default answer and construct the prompt
case "$default" in if [[ $default_answer == "Y" ]]; then
y) prompt="Y/n" ;; prompt="${question} (Y/n)? "
n) prompt="y/N" ;; else
*) printf "Invalid default answer\n"; exit 1 ;; prompt="${question} (y/N)? "
esac fi
# Use stty to make read command work for single character input
old_stty_cfg=$(stty -g)
stty raw -echo
printf "%s" "$prompt"
answer=$( while ! head -c 1 | grep -i '[yn]'; do true; done )
stty $old_stty_cfg
while true; do # If no answer is given, use the default answer
trap 'exit' INT
printf "%s (%s): " "$1" "$prompt"
read -r answer || exit
if [ -z "$answer" ]; then if [ -z "$answer" ]; then
answer="$default" answer=$default_answer
break
fi fi
case "$answer" in
y|Y) answer="y"; break;;
n|N) answer="n"; break;;
esac
done
case "$answer" in # Print the answer and return appropriate exit code
y|Y) printf "1";; printf "%s\n" "$answer"
n|N) printf "0";; if [[ $answer == "Y" || $answer == "y" ]]; then
esac exit 0
} else
exit 1
ask_yn "$@" fi

Loading…
Cancel
Save