Browse Source

ask_yn works perfectly!

main
deicidus 1 year ago
parent
commit
82dd57835f
  1. 17
      spells/cantrips/ask_yn

17
spells/cantrips/ask_yn

@ -10,15 +10,23 @@ else
prompt="${question} (y/N)? "
fi
# Save previous stty config
old_stty_cfg=$(stty -g)
# Handle Ctrl-C
trap "printf '\n'; exit 2" 2
trap "stty '$old_stty_cfg'; printf '\n'; exit 2" 2
# Use stty to make read command work for single character input
old_stty_cfg=$(stty -g)
stty raw -echo
printf "%s" "$prompt" >&2
answer=$( while ! head -c 1 | grep -i '[yn]'; do true; done )
stty "$old_stty_cfg" >&2
while IFS= read -r -n1 answer
do
if [ "$answer" = "" ] || echo "$answer" | grep -iq "^y\|^n"
then
break
fi
done
stty "$old_stty_cfg" >&2 # Restore original stty configuration
# If no answer is given, use the default answer
if [ -z "$answer" ]; then
@ -27,7 +35,6 @@ fi
# Print the answer and return appropriate exit code
printf "%s\n" "$(echo $answer | tr a-z A-Z)" >&2
sleep 0.01 # Without this, answer gets overwritten by next echo
if [ "$answer" = "Y" -o "$answer" = "y" ]; then
exit 0
else

Loading…
Cancel
Save