Last active
August 29, 2015 14:13
-
-
Save vaibhaw/5342e84be7bb6d9a2ac1 to your computer and use it in GitHub Desktop.
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
# path_tools.bash | |
# Ref - http://stackoverflow.com/a/294025 | |
# A set of tools for manipulating ":" separated lists like the | |
# canonical $PATH variable. | |
# | |
# /bin/sh compatibility can probably be regained by replacing $( ) | |
# style command expansion with ` ` style | |
############################################################################### | |
# Usage: | |
# | |
# To remove a path: | |
# replace_path PATH /exact/path/to/remove | |
# replace_path_pattern PATH <grep pattern for target path> | |
# | |
# To replace a path: | |
# replace_path PATH /exact/path/to/remove /replacement/path | |
# replace_path_pattern PATH <target pattern> /replacement/path | |
# | |
############################################################################### | |
# Remove or replace an element of $1 | |
# | |
# $1 name of the shell variable to set (e.g. PATH) | |
# $2 the precise string to be removed/replaced | |
# $3 the replacement string (use "" for removal) | |
function replace_path () { | |
path=$1 | |
list=$(eval echo '$'$path) | |
remove=$2 | |
replace=$3 # Allowed to be empty or unset | |
export $path=$(echo "$list" | tr ":" "\n" | sed "s:^$remove\$:$replace:" | | |
tr "\n" ":" | sed 's|:$||') | |
} | |
# Remove or replace an element of $1 | |
# | |
# $1 name of the shell variable to set (e.g. PATH) | |
# $2 a grep pattern identifying the element to be removed/replaced | |
# $3 the replacement string (use "" for removal) | |
function replace_path_pattern () { | |
path=$1 | |
list=$(eval echo '$'$path) | |
removepat=$2 | |
replacestr=$3 # Allowed to be empty or unset | |
removestr=$(echo "$list" | tr ":" "\n" | grep -m 1 "^$removepat\$") | |
replace_path "$path" "$removestr" "$replacestr" | |
} | |
############################################################################### | |
# Usage: | |
# Ref: https://stackoverflow.com/a/5048977/925216 | |
# To append path: | |
# append_path "/test:$HOME/bin:/example/my dir/space is not an issue" | |
# preserves folder order | |
############################################################################### | |
append_path() | |
{ | |
SAVED_IFS="$IFS" | |
IFS=: | |
for dir in $1 ; do | |
if ! $( echo "$PATH" | tr ":" "\n" | grep -qx "$dir" ) ; then | |
PATH=$PATH:$dir | |
fi | |
done | |
IFS="$SAVED_IFS" | |
unset dir | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment