make path_add more correct for dash
[distro-setup] / path_add-function
1 #!/bin/bash
2 # no bashisms so it can be used in debian profile run by dash
3 # --start adds to start of path, which will give it highest priority
4 # --ifexists will add to path only if the directory exists
5 path_add() {
6 local found x y z ifexists start loop
7 ifexists=false
8 start=false
9 loop=true
10 # portable substring matching is ugly http://mywiki.wooledge.org/BashFAQ/041
11 while $loop; do
12 case $1 in
13 --*)
14 if [ "$1" = --start ]; then
15 start=true
16 elif [ "$1" = --ifexists ]; then
17 ifexists=true
18 fi
19 shift
20 ;;
21 *)
22 loop=false
23 ;;
24 esac
25 done
26 for x in "$@"; do
27 found=false
28 IFS=:
29 for y in $PATH; do
30 [ "$x" = "$y" ] && found=true
31 done
32 unset IFS
33 if ! $found; then
34 if ! $ifexists || [ -d "$x" ]; then
35 if [ ! "$PATH" ]; then
36 PATH="$x"
37 elif $start; then
38 PATH="$x:$PATH"
39 else
40 PATH="$PATH:$x"
41 fi
42 fi
43 fi
44 done
45 }