Browse Source

fixed ask_yn

main
deicidus 2 years ago
parent
commit
91134967ff
  1. 48
      spells/cantrips/ask_yn

48
spells/cantrips/ask_yn

@ -6,39 +6,31 @@
ask_yn() {
default=${2:-"y"}
default=$(echo "$default" | tr '[:upper:]' '[:lower:]')
if [ "$default" = "y" ]; then
prompt="${1} (Y/n): "
default_output=1
else
prompt="${1} (y/N): "
default_output=0
fi
while true; do
# Show prompt and get user input
printf "%s" "$prompt"
if [ "$(uname)" = "Darwin" ]; then
# On macOS, use "read -n 1"
read -n 1 -r REPLY
else
# On Linux and others, use "read -n 1 -s"
read -r -n 1 -s REPLY
fi
# Set prompt string
case "$default" in
y) prompt="Y/n" ;;
n) prompt="y/N" ;;
*) echo "Invalid default answer"; exit 1 ;;
esac
# If user hits Ctrl+C or Enter, break and return default output
if [ -z "$REPLY" ] || [ "$REPLY" = "$(printf '\003')" ]; then
REPLY=$default
while true; do
echo -n "$1 ($prompt): "
stty raw -echo
answer=$(head -c 1) || exit
stty -echo
printf "\n"
break
fi
case "$REPLY" in
y|Y ) printf "\n"; return 1;;
n|N ) printf "\n"; return 0;;
* ) printf "\nInvalid input. Please type 'y' or 'n'.";;
case "$answer" in
"" ) answer="$default"; break;;
y|Y) answer="y"; break;;
n|N) answer="n"; break;;
esac
done
return $default_output
case "$answer" in
y|Y) echo 1;;
n|N) echo 0;;
esac
}
ask_yn "$@"
Loading…
Cancel
Save