Browse Source

fixed ask_yn

main
deicidus 2 years ago
parent
commit
be544decf9
  1. 54
      spells/cantrips/ask_yn

54
spells/cantrips/ask_yn

@ -1,35 +1,47 @@
#!/bin/sh #!/bin/sh
# Define ask_yn, which asks a yes or no question and outputs the result as 1 for Yes and 0 for No. # Define ask_yn, which asks a yes or no question and defaults to the specified choice.
# Takes two arguments: # Outputs 1 for yes and 0 for no
# $1: The question to be asked.
# $2: The default answer, either "y" or "n".
ask_yn() { ask_yn() {
question=$1 default=${2:-"y"}
default_answer=$2 default=$(echo "$default" | tr '[:upper:]' '[:lower:]')
if [ "$default" = "y" ]; then
# Capitalize the default option correctly prompt="${1} (Y/n): "
if [ "$default_answer" = "n" ] || [ "$default_answer" = "N" ]; then default_output=1
prompt="${question} (y/N): "
else else
prompt="${question} (Y/n): " prompt="${1} (y/N): "
default_output=0
fi fi
while true; do while true; do
# Show prompt and get user input
printf "%s" "$prompt" printf "%s" "$prompt"
STTY_CONFIG=$(stty -g) # Save current stty config if [ "$(uname)" = "Darwin" ]; then
stty raw -echo # Disable echo # On macOS, use "read -n 1"
ANSWER=$(head -c 1) # Scrape terminal input read -n 1 -r REPLY
stty $STTY_CONFIG # Restore stty config else
# On Linux and others, use "read -n 1 -s"
read -r -n 1 -s REPLY
fi
# If user hits Ctrl+C or Enter, break and return default output
if [ -z "$REPLY" ] || [ "$REPLY" = "$(printf '\003')" ]; then
REPLY=$default
printf "\n"
break
fi
case $ANSWER in case "$REPLY" in
[Yy] ) echo "Y"; exit 1;; # Yes: exit with 1 y|Y ) printf "\n"; return 1;;
[Nn] ) echo "N"; exit 0;; # No: exit with 0 n|N ) printf "\n"; return 0;;
"" ) if [ "$default_answer" = "n" ] || [ "$default_answer" = "N" ]; then echo "N"; exit 0; else echo "Y"; exit 1; fi;; # Default: exit with the default value * ) printf "\nInvalid input. Please type 'y' or 'n'.";;
* ) printf "\nPlease answer Yes or No.\n";;
esac esac
done done
return $default_output
} }
ask_yn "$@" # Call the function if this script is being run directly
if [ "${BASH_SOURCE[0]}" = "$0" ]; then
ask_yn "$@"
fi
Loading…
Cancel
Save