lots of updates
[distro-setup] / path_add-function
1 #!/bin/bash
2 # avoiding bashisms so it can be used in edge cases where I don't have bash,
3 # however, I'm not super confident that I've avoided them all
4 #
5 #
6 path_add() {
7 local help="usage: path_add [options] PATH
8 --help: print this
9 --end: adds to end of path, which will give it lowest priority
10 --ifexists: add to path only if the directory exists"
11 local found x y z ifexists end loop newpath
12 force=false
13 end=false
14 loop=true
15 # portable substring matching is ugly http://mywiki.wooledge.org/BashFAQ/041
16 while $loop; do
17 case $1 in
18 --*)
19 if [ "$1" = --end ]; then
20 end=true
21 elif [ "$1" = --force ]; then
22 force=true
23 elif [ "$1" = --help ]; then
24 echo "$help"
25 return
26 fi
27 shift
28 ;;
29 *)
30 loop=false
31 ;;
32 esac
33 done
34 IFS=:
35 # build up the path without the components we want to add
36 for y in $PATH; do
37 for x in "$@"; do
38 if [ "$x" = "$y" ]; then
39 found=true
40 else
41 found=false
42 fi
43 done
44 if ! $found; then
45 if [ ! "$newpath" ]; then
46 newpath="$y"
47 else
48 newpath="$newpath:$y"
49 fi
50 fi
51 done
52
53 unset IFS
54 PATH="$newpath"
55 for x in "$@"; do
56 x="$(readlink -f "$x")"
57 if $force || [ -d "$x" ]; then
58 if [ ! "$PATH" ]; then
59 PATH="$x"
60 elif $end; then
61 PATH="$PATH:$x"
62 else
63 PATH="$x:$PATH"
64 fi
65 fi
66 done
67 }