Browse Source

fixed ask_yn maybe

main
deicidus 2 years ago
parent
commit
b162f452cc
  1. 61
      spells/cantrips/ask_yn

61
spells/cantrips/ask_yn

@ -1,34 +1,31 @@
#!/bin/sh
#!/bin/bash
ask_yn() {
default=${2:-"y"}
default=$(printf "%s" "$default" | tr '[:upper:]' '[:lower:]')
# Set prompt string
case "$default" in
y) prompt="Y/n" ;;
n) prompt="y/N" ;;
*) printf "Invalid default answer\n"; exit 1 ;;
esac
while true; do
trap 'exit' INT
printf "%s (%s): " "$1" "$prompt"
read -r answer || exit
if [ -z "$answer" ]; then
answer="$default"
break
fi
case "$answer" in
y|Y) answer="y"; break;;
n|N) answer="n"; break;;
esac
done
case "$answer" in
y|Y) printf "1";;
n|N) printf "0";;
esac
}
question=$1
default_answer=$2
ask_yn "$@"
# Capitalize the default answer and construct the prompt
if [[ $default_answer == "Y" ]]; then
prompt="${question} (Y/n)? "
else
prompt="${question} (y/N)? "
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
# If no answer is given, use the default answer
if [ -z "$answer" ]; then
answer=$default_answer
fi
# Print the answer and return appropriate exit code
printf "%s\n" "$answer"
if [[ $answer == "Y" || $answer == "y" ]]; then
exit 0
else
exit 1
fi

Loading…
Cancel
Save