Skip to content

Commit a3b3057

Browse files
committed
Add new build_path() function for building PATH(-like) variables
1 parent 7b56bf3 commit a3b3057

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

source.sh

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,39 @@ function verbose_print() {
186186
}
187187

188188

189+
# DESC: Combines two path variables and removes any duplicates
190+
# ARGS: $1 (required): Path(s) to join with the second argument
191+
# $2 (optional): Path(s) to join with the first argument
192+
# OUTS: $build_path: The constructed path
193+
# NOTE: Heavily inspired by: https://unix.stackexchange.com/a/40973
194+
function build_path() {
195+
if [[ -z ${1-} || $# -gt 2 ]]; then
196+
script_exit "Invalid arguments passed to build_path()!" 2
197+
fi
198+
199+
local new_path path_entry temp_path
200+
201+
temp_path="$1:"
202+
if [[ -n ${2-} ]]; then
203+
temp_path="$temp_path$2:"
204+
fi
205+
206+
new_path=
207+
while [[ -n $temp_path ]]; do
208+
path_entry="${temp_path%%:*}"
209+
case "$new_path:" in
210+
*:"$path_entry":*) ;;
211+
*) new_path="$new_path:$path_entry"
212+
;;
213+
esac
214+
temp_path="${temp_path#*:}"
215+
done
216+
217+
# shellcheck disable=SC2034
218+
build_path="${new_path#:}"
219+
}
220+
221+
189222
# DESC: Check a binary exists in the search path
190223
# ARGS: $1 (required): Name of the binary to test for existence
191224
# $2 (optional): Set to any value to treat failure as a fatal error

template.sh

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,39 @@ function verbose_print() {
190190
}
191191

192192

193+
# DESC: Combines two path variables and removes any duplicates
194+
# ARGS: $1 (required): Path(s) to join with the second argument
195+
# $2 (optional): Path(s) to join with the first argument
196+
# OUTS: $build_path: The constructed path
197+
# NOTE: Heavily inspired by: https://unix.stackexchange.com/a/40973
198+
function build_path() {
199+
if [[ -z ${1-} || $# -gt 2 ]]; then
200+
script_exit "Invalid arguments passed to build_path()!" 2
201+
fi
202+
203+
local new_path path_entry temp_path
204+
205+
temp_path="$1:"
206+
if [[ -n ${2-} ]]; then
207+
temp_path="$temp_path$2:"
208+
fi
209+
210+
new_path=
211+
while [[ -n $temp_path ]]; do
212+
path_entry="${temp_path%%:*}"
213+
case "$new_path:" in
214+
*:"$path_entry":*) ;;
215+
*) new_path="$new_path:$path_entry"
216+
;;
217+
esac
218+
temp_path="${temp_path#*:}"
219+
done
220+
221+
# shellcheck disable=SC2034
222+
build_path="${new_path#:}"
223+
}
224+
225+
193226
# DESC: Check a binary exists in the search path
194227
# ARGS: $1 (required): Name of the binary to test for existence
195228
# $2 (optional): Set to any value to treat failure as a fatal error

0 commit comments

Comments
 (0)