-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathread_var.sh
executable file
·74 lines (62 loc) · 1.72 KB
/
read_var.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
68
69
70
71
72
73
#!/bin/bash
read_var() {
VAR_NAME=$1; shift
MESSAGE=$1; shift
REQUIRED=$1; shift
DEFAULT=$1; shift
# If a set of choices has been provided
if [[ -n $1 ]]; then
read -r -a CHOICES < <(echo "$*")
else
CHOICES=()
fi
# Preparing default message
DEFAULT_MSG=" [${DEFAULT}]"
# Save cursor and clear rest of screen
tput sc
tput ed
while true; do
# Write valid choices
if [[ ${#CHOICES[@]} -gt 0 ]]; then
tput el
tput cud 1
tput el
printf "Valid options: [%s]\n" "${CHOICES[@]}"
tput cuu 2
fi
tput el
echo -n "${MESSAGE}${DEFAULT_MSG}: "
read -r value
[[ -z ${value} && -n ${DEFAULT} ]] && value=${DEFAULT}
# Value is empty but marked as required
if [[ -z "${value}" && "${REQUIRED}" = "true" ]]; then
tput el
echo "You must provide a value (press ENTER to try again)"
read -r
tput rc
tput ed
continue
fi
# If choices provided, validate
if [[ ${#CHOICES[@]} -gt 0 ]]; then
found=false
for choice in "${CHOICES[@]}"; do
if [[ "${choice}" == "${value}" ]]; then
found=true
break
fi
done
tput el
if [[ ${found} == false ]]; then
echo "Invalid choice (press ENTER to try again)"
read -r
tput rc
tput ed
continue
fi
fi
# All good
eval "$VAR_NAME=\"${value}\""
break
done
}