-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprompt_yn.sh
More file actions
89 lines (84 loc) · 1.99 KB
/
prompt_yn.sh
File metadata and controls
89 lines (84 loc) · 1.99 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# scriptlet:_common/is_noninteractive.sh
##
# Prompt user for a yes or no response
#
# Arguments:
# --invert Invert the response (yes becomes 0, no becomes 1)
# --default-yes Default to yes if no response is given
# --default-no Default to no if no response is given
# -q Quiet mode (no output text after response)
#
# Returns:
# 1 for yes, 0 for no (or inverted if --invert is set)
#
# CHANGELOG:
# 2025.12.16 - Add text output for non-interactive and empty responses
# 2025.11.23 - Use is_noninteractive to handle non-interactive mode
# 2025.11.09 - Add -q (quiet) option to suppress output after prompt (and use return value)
# 2025.01.01 - Initial version
#
function prompt_yn() {
local TRUE=0 # Bash convention: 0 is success/true
local YES=1
local FALSE=1 # Bash convention: non-zero is failure/false
local NO=0
local DEFAULT="n"
local DEFAULT_CODE=1
local PROMPT="Yes or no?"
local RESPONSE=""
local QUIET=0
while [ $# -ge 1 ]; do
case $1 in
--invert) YES=0; NO=1 TRUE=1; FALSE=0;;
--default-yes) DEFAULT="y";;
--default-no) DEFAULT="n";;
-q) QUIET=1;;
*) PROMPT="$1";;
esac
shift
done
echo "$PROMPT" >&2
if [ "$DEFAULT" == "y" ]; then
DEFAULT_TEXT="yes"
DEFAULT="$YES"
DEFAULT_CODE=$TRUE
echo -n "> (Y/n): " >&2
else
DEFAULT_TEXT="no"
DEFAULT="$NO"
DEFAULT_CODE=$FALSE
echo -n "> (y/N): " >&2
fi
if is_noninteractive; then
# In non-interactive mode, return the default value
echo "$DEFAULT_TEXT (default non-interactive)" >&2
if [ $QUIET -eq 0 ]; then
echo $DEFAULT
fi
return $DEFAULT_CODE
fi
read RESPONSE
case "$RESPONSE" in
[yY]*)
if [ $QUIET -eq 0 ]; then
echo $YES
fi
return $TRUE;;
[nN]*)
if [ $QUIET -eq 0 ]; then
echo $NO
fi
return $FALSE;;
"")
echo "$DEFAULT_TEXT (default choice)" >&2
if [ $QUIET -eq 0 ]; then
echo $DEFAULT
fi
return $DEFAULT_CODE;;
*)
if [ $QUIET -eq 0 ]; then
echo $DEFAULT
fi
return $DEFAULT_CODE;;
esac
}