From 82dd57835f1024b84f69d8ea9a984d0c55beb136 Mon Sep 17 00:00:00 2001 From: deicidus Date: Thu, 8 Jun 2023 14:42:41 -0700 Subject: [PATCH] ask_yn works perfectly! --- spells/cantrips/ask_yn | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/spells/cantrips/ask_yn b/spells/cantrips/ask_yn index 6e59b88..af22c7c 100755 --- a/spells/cantrips/ask_yn +++ b/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