fix vpn host naming
[distro-setup] / path_add-function
1 #!/bin/bash
2 # Copyright (C) 2016 Ian Kelling
3
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7
8 # http://www.apache.org/licenses/LICENSE-2.0
9
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16
17 # avoiding bashisms so it can be used in edge cases where I don't have bash,
18 # however, I'm not super confident that I've avoided them all
19 #
20 path_add() {
21 local help="usage: path_add [options] PATH
22 --help: print this
23 --end: adds to end of path, which will give it lowest priority
24 --ifexists: add to path only if directory exists"
25 local found x y ifexists end loop newpath
26 ifexists=false
27 end=false
28 loop=true
29 # portable substring matching is ugly http://mywiki.wooledge.org/BashFAQ/041
30 while $loop; do
31 case $1 in
32 --*)
33 if [ "$1" = --end ]; then
34 end=true
35 elif [ "$1" = --ifexists ]; then
36 ifexists=true
37 elif [ "$1" = --help ]; then
38 echo "$help"
39 return
40 fi
41 shift
42 ;;
43 *)
44 loop=false
45 ;;
46 esac
47 done
48 IFS=:
49 # build up the path without the components we want to add
50 for y in $PATH; do
51 for x in "$@"; do
52 if [ "$x" = "$y" ]; then
53 found=true
54 else
55 found=false
56 fi
57 done
58 if ! $found; then
59 if [ ! "$newpath" ]; then
60 newpath="$y"
61 else
62 newpath="$newpath:$y"
63 fi
64 fi
65 done
66
67 unset IFS
68 PATH="$newpath"
69 for x in "$@"; do
70 if ! $ifexists || [ -d "$x" ]; then
71 if [ ! "$PATH" ]; then
72 PATH="$x"
73 elif $end; then
74 PATH="$PATH:$x"
75 else
76 PATH="$x:$PATH"
77 fi
78 fi
79 done
80 }