Created
July 31, 2022 15:07
-
-
Save prenaux/b3822a091d83b5ddce24fa588713340f to your computer and use it in GitHub Desktop.
Add/remove path from the PATH environment variable
This file contains hidden or 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
| pathenv_add() { | |
| if [ ! -d "$1" ]; then | |
| return 0 | |
| fi | |
| DIR=$(unxpath "$1") | |
| if [ -z "$PATH" ]; then | |
| PATH=$DIR | |
| elif [ -d "$DIR" ] && [[ ":$PATH:" != *":$DIR:"* ]] ; then | |
| if [ "$2" = "after" ] ; then | |
| export PATH=$PATH:$DIR | |
| else | |
| export PATH=$DIR:$PATH | |
| fi | |
| fi | |
| } | |
| pathenv_remove() { | |
| local D=":${PATH}:"; | |
| [ "${D/:$1:/:}" != "$D" ] && PATH="${D/:$1:/:}"; | |
| PATH="${PATH/#:/}"; | |
| export PATH="${PATH/%:/}"; | |
| } | |
| pathenv_remove_add() { | |
| pathenv_remove "$1" | |
| pathenv_add "$1" "$2" | |
| } |
This file contains hidden or 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
| # From: https://unix.stackexchange.com/a/479316 | |
| # Calling example: | |
| # append_to PATH "/usr/local/bin" | |
| function remove_from() | |
| { | |
| local path="${1}" | |
| local dir="${2}" | |
| local -a dirs=() | |
| local old_ifs="${IFS}" | |
| IFS=":" | |
| set -- ${!path} | |
| while [ "$#" -gt "0" ] | |
| do | |
| [ "${1}" != "${dir}" ] && dirs+=("${1}") | |
| shift | |
| done | |
| eval "export ${path}=\"${dirs[*]}\"" | |
| IFS="${old_ifs}" | |
| } | |
| function append_to() | |
| { | |
| remove_from "${1}" "${2}" | |
| [ -d "${2}" ] || return | |
| if [ -n "${!1}" ] | |
| then | |
| eval "export ${1}=\"${!1}:${2}\"" | |
| else | |
| eval "export ${1}=\"${2}\"" | |
| fi | |
| } | |
| function prepend_to() | |
| { | |
| remove_from "${1}" "${2}" | |
| [ -d "${2}" ] || return | |
| if [ -n "${!1}" ] | |
| then | |
| eval "export ${1}=\"${2}:${!1}\"" | |
| else | |
| eval "export ${1}=\"${2}\"" | |
| fi | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment