by t43562 · 1y ago · 0 comments
path_add() {
export PATH=$PATH:$(string_join ':' $@)
}
path_prepend() {
PATH=$(string_join ':' "$@"):$PATH
export PATH
}
These can join an arbitrary list of paths to PATH. e.g. path_add /usr/bin /usr/local/bin ~/bin
They depend on another one: string_join() {
local join=$1; shift
local result=$1; shift
for p in "$@"; do
result="${result}${join}${p}"
done
echo -n "$result"
set +x
}
I also have ones for adding and prepending to LD_LIBRARY_PATHIn Bash:
path_append() { local p; for p; do [[ :"$PATH": =~ :"$p": ]] || PATH+=:$p; done; }
path_prepend() { local p; for p; do [[ :"$PATH": =~ :"$p": ]] || PATH=$p:$PATH; done; }
In portable POSIX shell: path_append() { for p; do case :"$PATH": in *:"$p":*) ;; *) export PATH="$PATH:$p" ;; esac; done; }
path_prepend() { for p; do case :"$PATH": in *:"$p":*) ;; *) export PATH="$p:$PATH" ;; esac; done; } ###################################################################
# Add directory to path
pathadd() {
newelement=${1%/}
if [ -d "$1" ] && ! echo $PATH | grep -E -q "(^|:)$newelement($|:)" ; then
if [ "$2" = "after" ] ; then
PATH="$PATH:$newelement"
else
PATH="$newelement:$PATH"
fi
fi
}
###################################################################
# Remove directory from path
pathrm() {
PATH="$(echo $PATH | sed -e "s;\(^\|:\)${1%/}\(:\|\$\);\1\2;g" -e \
's;^:\|:$;;g' -e 's;::;:;g')"
}"export PATH=$DIR:$PATH - That particular pattern is way too common, and is very dangerous if you consider the case when [$DIR or] $PATH (or whatever your variable is, like $LD_LIBRARY_PATH) isn’t set. Then, the value will be :/path/to/dir, which usually means both /path/to/dir and the current directory, which is usually both unexpected behaviour and a security concern."
Your function does that so +1. Though I'd use
[[ $PATH =~ "(^|:)$newelement($|:)" ]]
over grep -q but it functions the same.