deicidus
1 year ago
1 changed files with 34 additions and 22 deletions
@ -1,35 +1,47 @@
|
||||
#!/bin/sh |
||||
|
||||
# Define ask_yn, which asks a yes or no question and outputs the result as 1 for Yes and 0 for No. |
||||
# Takes two arguments: |
||||
# $1: The question to be asked. |
||||
# $2: The default answer, either "y" or "n". |
||||
# Define ask_yn, which asks a yes or no question and defaults to the specified choice. |
||||
# Outputs 1 for yes and 0 for no |
||||
|
||||
ask_yn() { |
||||
question=$1 |
||||
default_answer=$2 |
||||
|
||||
# Capitalize the default option correctly |
||||
if [ "$default_answer" = "n" ] || [ "$default_answer" = "N" ]; then |
||||
prompt="${question} (y/N): " |
||||
default=${2:-"y"} |
||||
default=$(echo "$default" | tr '[:upper:]' '[:lower:]') |
||||
if [ "$default" = "y" ]; then |
||||
prompt="${1} (Y/n): " |
||||
default_output=1 |
||||
else |
||||
prompt="${question} (Y/n): " |
||||
prompt="${1} (y/N): " |
||||
default_output=0 |
||||
fi |
||||
|
||||
|
||||
while true; do |
||||
# Show prompt and get user input |
||||
printf "%s" "$prompt" |
||||
STTY_CONFIG=$(stty -g) # Save current stty config |
||||
stty raw -echo # Disable echo |
||||
ANSWER=$(head -c 1) # Scrape terminal input |
||||
stty $STTY_CONFIG # Restore stty config |
||||
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 |
||||
|
||||
case $ANSWER in |
||||
[Yy] ) echo "Y"; exit 1;; # Yes: exit with 1 |
||||
[Nn] ) echo "N"; exit 0;; # No: exit with 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 "\nPlease answer Yes or No.\n";; |
||||
# 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 "$REPLY" in |
||||
y|Y ) printf "\n"; return 1;; |
||||
n|N ) printf "\n"; return 0;; |
||||
* ) printf "\nInvalid input. Please type 'y' or 'n'.";; |
||||
esac |
||||
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…
Reference in new issue