You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
35 lines
1.1 KiB
35 lines
1.1 KiB
#!/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". |
|
|
|
ask_yn() { |
|
question=$1 |
|
default_answer=$2 |
|
|
|
# Capitalize the default option correctly |
|
if [ "$default_answer" = "n" ] || [ "$default_answer" = "N" ]; then |
|
prompt="${question} (y/N): " |
|
else |
|
prompt="${question} (Y/n): " |
|
fi |
|
|
|
while true; do |
|
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 |
|
|
|
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";; |
|
esac |
|
done |
|
} |
|
|
|
ask_yn "$@" |