-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathconfirm.sh
executable file
·67 lines (57 loc) · 1 KB
/
confirm.sh
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
#!/usr/bin/env bash
# [yes/no question] [command]
# Ask a yes/no question, and optionally execute a command
confirm() {
local default= d= # default answer [y|n]
local optional= o= # do not return failure if the user cancels
local tty= t= # force tty input
eval "$(ally)"
local prompt="$*"
local is_command=
if [[ $prompt != *\? ]]; then
prompt="$prompt ?"
is_command=1
fi
local confirmed=
ask_them() {
read -r -n 1 -p "$prompt " yn
echo
}
confirm_loop() {
while true; do
ask_them
case "${yn:-${default}}" in
y*|Y*)
confirmed=1
break
;;
n*|N*)
break
;;
'')
if [ -n "$default" ]; then
confirmed=${default,,}
break
fi
;;
*)
echo -n "! [yn] "
;;
esac
done
}
if [ -n "$tty" ]; then
confirm_loop < /dev/tty > /dev/tty 2>&1
else
confirm_loop
fi
if [ -n "$confirmed" ]; then
if [ -n "$is_command" ]; then "$@"; fi
return 0
else
return "${optional:-1}"
fi
}
if [ "${BASH_SOURCE[0]}" = "$0" ]; then
confirm "$@"
fi