-
Notifications
You must be signed in to change notification settings - Fork 0
/
ask
executable file
·70 lines (52 loc) · 2.01 KB
/
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/usr/bin/env bash
[[ "${1,,}" != +(\-)@(h)?(elp) ]] || { cat <<'EOL'
USAGE:
ask [<OPTION>] [<QUESTION>]
SYNOPSIS:
Prompt the user with an ostensibly yes-or-no QUESTION (all input is optional).
Returns 0(true) for (y|yes), or 1(false) for (n|no).
If no QUESTION is provided it will simply prompt for a '(Y/n)' response.
Response is case-insensitive.
OPTIONS:
(*) OPTIONS must precede QUESTION if supplied.
(*) Trailing args always comprise QUESTION (escapes are interpretted).
-h,--help show this helpful usage information
-y,--yes fail if answer is not (y|yes)
-n,--no fail if answer is not (n|no)
-l, repeatedly ask [<QUESTION>] until a desired response is given.
--loop the desired response can be set using the (`-y`|`--yes`) and (`-n`|`--no`) flags,
(default is (y|yes) )
-s, ask [<QUESTION>] again if a response
--strict other than (y|yes) or (n|no) is given
-p, write the response to STDOUT
--prompt (deactivates all other options)
(causes `ask` to function as a simple read prompt)
(optional: ` --prompt=MESSAGE `)
EOL
exit 0
}
shopt -s extglob
Ask='Ask'
Desire='@(y)?(es)'
PromptLine='(response): '
for((p=0,a=1;a<=$#;a++)){
case "${!a,,}" in
'-y'|'--yes') ((p=a)) ;;
'-n'|'--no') ((p=a)); Desire='@(n)?(o)' ;;
'-s'|'--strict') ((p=a)); Ask='Strict' ;;
'-l'|'--loop') ((p=a)); Action='Pester' ;;
+(\-)@(p)?(rompt)?(\=)*) ((p=a)); Action='Tell'
[[ "${!a}" != *\=* ]] || PromptLine="${!a#*\=}" ;;
*) continue
esac
}
Ask() { local Ans ; printf "${*:2}\n" ; read -p '(Y/n): ' Ans ; [[ "${Ans,,}" == ${1} ]] ; }
Strict() {
printf "${*:2}\n"
read -p '(Y/n): ' Ans
[[ "${Ans,,}" == @(n?(o)|y?(es)) ]] || Strict ${1} "${*:2}"
[[ "${Ans,,}" == $1 ]]
}
Pester() { $Ask "$1" "${@:2}" || Pester "$1" "${*:2}"; }
Tell() { local Ans; printf "${*:2}\n" >/dev/stderr || true; read -p "$PromptLine" Ans ; echo "$Ans"; }
${Action:-$Ask} "$Desire" "${*:$((++p))}"