about summary refs log tree commit diff stats
path: root/profile/00_functions.sh
blob: 4bf0c78d42c1ba5adb91805a5f390bb75f1718a1 (plain)
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
# utility functions for all shells
# these should be POSIX-compatible.

# add a path to PATH, but only if it's not already there
path_add_to_PATH() { # path_add_to_PATH [-a] PATH...
	# -a appends (default is prepend)
	APPEND=false
	if [ "x$1" = "x-a" ]; then
		APPEND=true
		shift
	fi

	for p; do
		case ":$PATH:" in
		*:"$p":*) ;;
		*)
			if $APPEND; then
				PATH="$PATH:$p"
			else
				PATH="$p:$PATH"
			fi
			;;
		esac
	done

	unset APPEND
}

# Generalization of `path_add_to_PATH' for any variable.
path_add_unsafe() { #path_add_unsafe [-a] [-d DELIM] VAR PATH...
	## Add PATH... to VAR, delimiting with DELIM (default :).
	# By default, the VAR will be prepended to; passing -a will append the
	# variable.  -d DELIM defines the delimiter.
	#
	# This function has the _unsafe suffix because it uses `eval' to set
	# variables.
	APPEND=false
	DELIM=:
	while getopts ad: opt; do
		case "$opt" in
		a) APPEND=true ;;
		d) DELIM="$OPTARG" ;;
		*) return 1 ;;
		esac
	done
	shift $(expr $OPTIND - 1)

	var="$1"
	shift

	for path; do
		case ":$(eval "echo \$$var"):" in
		*:"$path":*) ;;
		*)
			if $APPEND; then
				eval "$var=\$$var${var:+$DELIM}$path"
			else
				eval "$var=$path${var:+$DELIM}\$$var"
			fi
			;;
		esac
	done
	unset -v APPEND DELIM var
}

# Re-source ~/.profile
reprofile() {
	. $HOME/.profile
}