deicidus
1 year ago
3 changed files with 87 additions and 77 deletions
@ -1,30 +0,0 @@
|
||||
#!/usr/bin/env sh |
||||
|
||||
# Define ask_Yn, which asks a yes or no question and saves the result in the given variable name (defaults to yes) |
||||
# Takes one arg, which is the variable name where the result will be saved |
||||
# No is 0 and Yes is 1 |
||||
|
||||
source say |
||||
|
||||
ask_Yn() { |
||||
if [ -n "$2" ]; then |
||||
say_inline "$2 (Y/n): " |
||||
fi |
||||
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 [ "$ANSWER" != "${ANSWER#[Nn]}" ]; then |
||||
say "N" |
||||
export "${1}=0" |
||||
else |
||||
say "Y" |
||||
export "${1}=1" |
||||
fi |
||||
} |
||||
|
||||
# Check if the script is being called from another script |
||||
if [ "${BASH_SOURCE[0]}" = "$0" ]; then |
||||
# If not, call the function |
||||
ask_Yn "$@" |
||||
fi |
@ -0,0 +1,35 @@
|
||||
#!/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 "$@" |
Loading…
Reference in new issue