Browse Source

ask_yn works perfectly!

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

17
spells/cantrips/ask_yn

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

Loading…
Cancel
Save