#!/usr/bin/env bash
# Add the path in $1 to the path variable in $2 if it's not there already, and print the updated path.
# E.g. PATH=$(add-to-path path/to/file PATH) adds 'path/to/file' to $PATH.
# Based on this StackExchange answer: https://superuser.com/a/39995

new_path_str="$1"
path_name="$2"
path_str="${!2}"

# ${!2} (bash) / ${(P)2} (zsh) evaluates to the value stored in the variable name stored in $2.

# Condition: $new_path_str is not in $path_str.
# Note how colons are handled in a smart way.
if [[ ":$path_str:" != *":$new_path_str:"* ]]; then

	# ${value:+new_value} evaluates to $new_value if $value is already set to a non-empty value.
	# This returns $path_str:$new_path_str, or just $new_path_str with no colons if $path_str is empty.   
	export "$path_name"="${path_str:+"$path_str:"}$new_path_str"
fi

echo ${!path_name}
