Skip to content

Instantly share code, notes, and snippets.

@meoow
Last active March 6, 2021 02:22
Show Gist options
  • Save meoow/7220dd53deb0c7f43656 to your computer and use it in GitHub Desktop.
Save meoow/7220dd53deb0c7f43656 to your computer and use it in GitHub Desktop.
append / prepend / remove path from PATH
addpath() { #{{{
local method path
if (($#==0));then
cat <<_EOF_
addpath [+|_|-] path [... pathN]
+ append path (default)
- remove path
_ prepend path
_EOF_
return
fi
case "$1" in
'+')
method=append
shift
;;
'_')
method=prepend
shift
;;
'-')
method=remove
shift
;;
esac
if [[ -z $method ]];then
method=append
fi
if [[ $method == append ]] || [[ $method == prepend ]];then
for path in "$@";do
if [[ :$PATH: == *:$path:* ]];then
continue
fi
if [[ ! -d "$path" ]];then
continue
fi
if [[ $method == append ]];then
PATH=$PATH:$path
else
PATH=$path:$PATH
fi
done
elif [[ $method == remove ]];then
local _PATH=:${PATH//:/::}:
for path in "$@";do
if [[ $_PATH == *:$path:* ]];then
_PATH=${_PATH//:$path:/}
fi
done
while true;do
if [[ $_PATH == *::* ]];then
_PATH=${_PATH//::/:}
else
break
fi
done
_PATH=${_PATH#:}
_PATH=${_PATH%:}
PATH=$_PATH
fi
} #}}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment