Browse Source

fixed ask_yn maybe

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

55
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
while true; do # Use stty to make read command work for single character input
trap 'exit' INT old_stty_cfg=$(stty -g)
printf "%s (%s): " "$1" "$prompt" stty raw -echo
read -r answer || exit printf "%s" "$prompt"
if [ -z "$answer" ]; then answer=$( while ! head -c 1 | grep -i '[yn]'; do true; done )
answer="$default" stty $old_stty_cfg
break
fi
case "$answer" in
y|Y) answer="y"; break;;
n|N) answer="n"; break;;
esac
done
case "$answer" in # If no answer is given, use the default answer
y|Y) printf "1";; if [ -z "$answer" ]; then
n|N) printf "0";; answer=$default_answer
esac fi
}
ask_yn "$@" # 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