-
Notifications
You must be signed in to change notification settings - Fork 282
/
ask
47 lines (37 loc) · 953 Bytes
/
ask
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#!/usr/bin/env bash
#
# Ask (https://djm.me/ask)
# This is a general-purpose function to ask yes/no questions in Bash, either
# with or without a default answer. It keeps repeating the question until it
# gets a valid answer.
# color variables
yellow=$(tput setaf 3)
reset=$(tput sgr0)
function ask() {
local prompt default reply
if [ "${2:-}" = "Y" ]; then
prompt="Y/n"
default=Y
elif [ "${2:-}" = "N" ]; then
prompt="y/N"
default=N
else
prompt="y/n"
default=
fi
while true; do
# Ask the question (not using "read -p" as it uses stderr not stdout)
echo -ne "${yellow}$1 [$prompt] ${reset}"
# Read the answer (use /dev/tty in case stdin is redirected from somewhere else)
read -r reply </dev/tty
# Default?
if [ -z "$reply" ]; then
reply=$default
fi
# Check if the reply is valid
case "$reply" in
Y* | y*) return 0 ;;
N* | n*) return 1 ;;
esac
done
}