-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathpath_manager
More file actions
83 lines (75 loc) · 2.14 KB
/
path_manager
File metadata and controls
83 lines (75 loc) · 2.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# Manage ':' separated variables, such as PATH, LD_LIBRARY_PATH
# Check whether a path exists in a var
_contains_path() {
local var_value=":$1:"
local target=":$2:"
# `$target` is quoted, so glob characters in it are matched literally
[[ "$var_value" == *"$target"* ]]
}
# Append a path to a path variable
# Example:
# path_var_append PATH /usr/local/bin
path_var_append() {
if [[ $# -ne 2 ]]; then
echo "Usage: ${FUNCNAME[0]} VARIABLE_NAME PATH" >&2
return 1
fi
local var_name="$1"
local new_path="$2"
local current_value
eval "current_value=\${$var_name}"
if ! _contains_path "$current_value" "$new_path"; then
if [[ -z "$current_value" ]]; then
export "$var_name=$new_path"
else
export "$var_name=$current_value:$new_path"
fi
fi
}
# Prepend a path to a path variable
# Example:
# path_var_prepend PATH /usr/local/bin
path_var_prepend() {
if [[ $# -ne 2 ]]; then
echo "Usage: ${FUNCNAME[0]} VARIABLE_NAME PATH" >&2
return 1
fi
local var_name="$1"
local new_path="$2"
local current_value
eval "current_value=\${$var_name}"
if ! _contains_path "$current_value" "$new_path"; then
if [[ -z "$current_value" ]]; then
export "$var_name=$new_path"
else
export "$var_name=$new_path:$current_value"
fi
fi
}
# Remove a path from path variable
# Example:
# path_var_remove PATH /usr/local/bin
path_var_remove() {
if [[ $# -ne 2 ]]; then
echo "Usage: ${FUNCNAME[0]} VARIABLE_NAME PATH" >&2
return 1
fi
local var_name="$1"
local remove_path="$2"
local current_value
eval "current_value=\${$var_name}"
local result=":"
local parts
# zsh uses `-A` for arrays; bash uses `-a`
if [[ -n "$ZSH_VERSION" ]]; then
IFS=':' read -rA parts <<< "$current_value"
else
IFS=':' read -ra parts <<< "$current_value"
fi
for part in "${parts[@]}"; do
[[ "$part" != "$remove_path" && -n "$part" ]] && result+="$part:"
done
result="${result#:}"
result="${result%:}"
export "$var_name=$result"
}