From b162f452cc1f27a6f31e57ab4fc489c89343c08c Mon Sep 17 00:00:00 2001 From: deicidus Date: Thu, 8 Jun 2023 11:35:28 -0700 Subject: [PATCH] fixed ask_yn maybe --- spells/cantrips/ask_yn | 61 ++++++++++++++++++++---------------------- 1 file changed, 29 insertions(+), 32 deletions(-) diff --git a/spells/cantrips/ask_yn b/spells/cantrips/ask_yn index 3ebc29b..4f8d26e 100755 --- a/spells/cantrips/ask_yn +++ b/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 "$@" \ No newline at end of file +# 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