deicidus
2 years ago
1 changed files with 34 additions and 22 deletions
@ -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 |
||||||
|
|
||||||
case $ANSWER in |
# If user hits Ctrl+C or Enter, break and return default output |
||||||
[Yy] ) echo "Y"; exit 1;; # Yes: exit with 1 |
if [ -z "$REPLY" ] || [ "$REPLY" = "$(printf '\003')" ]; then |
||||||
[Nn] ) echo "N"; exit 0;; # No: exit with 0 |
REPLY=$default |
||||||
"" ) 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 "\n" |
||||||
* ) printf "\nPlease answer Yes or No.\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 |
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…
Reference in new issue