-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsh.sh
More file actions
71 lines (51 loc) · 1.92 KB
/
Copy pathsh.sh
File metadata and controls
71 lines (51 loc) · 1.92 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
#!/usr/bin/bash
if [ -n "$sh_isSourced" ] || [ -n "$sh_initialOptions" ]; then return; fi
. "validate.sh" && validate_shellVersion
declare -gri sh_isSourced=1
################################################################################
# Options ######################################################################
sh_saveOptions() {
. "log.sh"
local add_readonly=0
local varName=""
local cmd_exists=("declare" "-gp")
local cmd_create=("declare" "-ga")
while (( $# > 0 )); do
case "$1" in
"-r"|"--add-readonly")
add_readonly=1
shift;;
*)
varName="$1"
shift
break;;
esac
done
(( $# != 0 )) && log_fatal -f "Invalid argument: ${1}"
[[ -z "$varName" || ! "$varName" =~ ^[a-zA-Z_][a-zA-Z0-9_]*$ ]] && \
log_fatal -f "Invalid variable name: ${varName}"
"${cmd_exists[@]}" "$varName" &>/dev/null && unset "$varName"
"${cmd_create[@]}" "$varName"
read -rs -a "$varName" <<< "$(set +o | sed -E ':a;N;$!ba;s/(set |\nset)//g')"
(( add_readonly )) && "${cmd_create[@]}" -r "$varName"
return 0
} ##############################################################################
sh_restoreOptions() {
. "log.sh"
local varName="$1"
local options=()
[[ -z "$varName" || ! "$varName" =~ ^[a-zA-Z_][a-zA-Z0-9_]*$ ]] && \
log_fatal -f "Invalid variable name: ${varName}"
! ( declare -p "$varName" 2>/dev/null | grep -qE '^declare \-a' ) && \
log_fatal -f "Invalid variable: ${varName}"
varName+="[@]"
options=("${!varName}")
(( ${#options[@]} == 0 || ${#options[@]} % 2 != 0 )) && \
log_fatal -f "Invalid options: ${options[@]}"
for (( i = 0; i < ${#options[@]}; i = i + 2 )); do
set "${options[i]}" "${options[i + 1]}"
done
return 0
} ##############################################################################
################################################################################
sh_saveOptions -r sh_initialOptions