Last active
June 16, 2016 18:46
-
-
Save tueda/6718638 to your computer and use it in GitHub Desktop.
Append/prepend/remove a path to/from an environment variable. Assumed no spaces in the path. #bash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# append_path VAR PATH - adds PATH to the end of PATH | |
append_path() { | |
[ $# -lt 2 ] && return | |
[ ! -d "$2" ] && echo "Warning: path $2 is not found on `hostname`" >&2 | |
remove_path $1 $2 | |
if eval '[ -z "$'$1'" ]'; then | |
eval $1=$2 | |
else | |
eval $1='$'$1:$2 | |
fi | |
export $1 | |
} | |
# prepend_path VAR PATH - adds PATH to the beginning of PATH | |
prepend_path() { | |
[ $# -lt 2 ] && return | |
[ ! -d "$2" ] && echo "Warning: path $2 is not found on `hostname`" >&2 | |
remove_path $1 $2 | |
if eval '[ -z "$'$1'" ]'; then | |
eval $1=$2 | |
else | |
eval $1=$2:'$'$1 | |
fi | |
export $1 | |
} | |
# remove_path VAR PATH - removes PATH from VAR | |
remove_path() { | |
[ $# -lt 2 ] && return | |
eval $1'=${'$1'//:$2/}' | |
eval $1'=${'$1'//$2:/}' | |
eval '[ "$'$1'" == "'$2'" ]' && eval $1= | |
export $1 | |
} | |
# set_path VAR PATH - sets VAR to PATH | |
set_path() { | |
[ ! -d "$2" ] && echo "Warning: path $2 is not found on `hostname`" >&2 | |
eval "$1=$2" | |
export $1 | |
} | |
# set_env VAR VALUE - sets VAR to VALUE | |
set_env() { | |
[ $# -lt 1 ] && return | |
eval "$1=$2" | |
export $1 | |
} | |
# append_path_c VAR PATH - same as append_path but without warnings | |
append_path_c() { | |
[ -d "$2" ] && append_path "$1" "$2" | |
} | |
# prepend_path_c VAR PATH - same as prepend_path but without warnings | |
prepend_path_c() { | |
[ -d "$2" ] && prepend_path "$1" "$2" | |
} | |
# set_path_c VAR PATH - same as set_path but without warnings | |
set_path_c() { | |
[ -d "$2" ] && set_path "$1" "$2" | |
} | |
# split_path [VAR] - prints VAR (default: PATH) split over lines | |
split_path() { | |
local path='$'${1:-PATH} | |
path=`eval "echo $path"` | |
local IFS=':' | |
for p in $path; do | |
echo "$p" | |
done | |
} | |
# clean_path [VAR] - removes duplicates in VAR (default: PATH) | |
clean_path() { | |
local var=${1:-PATH} | |
local val=$(eval "echo \$$var" \ | |
| awk -v RS=: -v ORS=: '!a[$1]++{if(NR>1)printf ORS;printf $a[$1]}') | |
eval "$var='$val'" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment