-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy patharrayutil
71 lines (68 loc) · 1.66 KB
/
arrayutil
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
#!/bin/bash
# without removes a component from its argument array, echoing the new array
# joined by IFS. For Example:
#
# $ PATH=/bin:/usr/bin:/usr/local/bin
# $ IFS=:; without /usr/local/bin $PATH
# /bin:/usr/bin
without()
{
arg="$1"
shift
out=()
for part in "$@"; do
if [ -n "$part" ] && [ "$part" != "$arg" ]; then
out+=($part)
fi
done
echo "${out[*]}"
}
# prepend adds a component to the head of its argument array, echoing the new
# array joined by IFS; the given component is deduped, and ensured to now come
# first. For example:
#
# $ PATH=/bin:/usr/bin:/usr/local/bin
# $ PATH=$(IFS=:; prepend /usr/local/bin $PATH)
# $ echo $PATH
# /usr/local/bin:/bin:/usr/bin
#
# $ PATH=$(IFS=:; prepend $HOME/bin $PATH)
# $ echo $PATH
# /home/bob/bin:/usr/local/bin:/bin:/usr/bin
prepend()
{
arg="$1"
shift
out=($arg)
for part in "$@"; do
if [ -n "$part" ] && [ "$part" != "$arg" ]; then
out+=($part)
fi
done
echo "${out[*]}"
}
# append adds a component to the tail of its argument array, echoing the new
# array joined by IFS; the given component is deduped, and ensured to now come
# last. For example:
#
# $ PATH=/bin:/usr/bin:/usr/local/bin
# $ PATH=$(IFS=:; prepend /usr/local/bin $PATH)
# $ echo $PATH
# /bin:/usr/bin:/usr/local/bin
#
# $ PATH=$(IFS=:; prepend $HOME/bin $PATH)
# $ echo $PATH
# /bin:/usr/bin:/usr/local/bin:/home/bob/bin
append()
{
arg="$1"
shift
out=()
for part in "$@"; do
if [ -n "$part" ] && [ "$part" != "$arg" ]; then
out+=($part)
fi
done
out+=($arg)
echo "${out[*]}"
}