-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgetyn
More file actions
executable file
·59 lines (46 loc) · 1.14 KB
/
getyn
File metadata and controls
executable file
·59 lines (46 loc) · 1.14 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
#!/bin/bash
#
# getyn
#
# getyn() $1
#
# Takes $1 for a prompt string
# Places true or false command into $2, which is an optional argument.
# User is prompted for (y/n) answer at the end of the prompt string.
#
usagestr=$(
cat <<EOF
$(basename $0) prompt
Given a prompt string, user is prompted for a y/n answer. Only y or n are
accepted as valid responses, so the prompt is presented in a loop until
the user types either y or n.
Returns 0 if response was y
Returns 1 if response was n
Note:
You cannot use this script if there is a pending read. For example,
the following will not function properly, because "\$lines" string
is being read by the while loop, so the read in getyn encounters
a buffer of pending characters.
while IFS= read line; do
getyn "Show this line?"
[ $? -eq 0 ] && echo "\$line"
done <<< "\$lines"
\0
EOF
)
usage() {
echo -e "$usagestr"
exit
}
[ "$1" == "-h" ] && usage
[ $# -gt 0 -a $# -le 1 ] || usage
declare promptstring="$1"
declare answer
while true; do
echo -en "$promptstring (y/n) : "
read -n1 answer
echo
[ "$answer" == "y" ] && exit 0
[ "$answer" == "n" ] && exit 1
echo "Please answer y or n."
done