Created
December 13, 2020 21:55
-
-
Save rawiriblundell/d9fdeafd76e7f31ac5301ea0687dafe1 to your computer and use it in GitHub Desktop.
Dynamically build PATH variable with a function that can also be used to append to the PATH
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
# A function to update the PATH variable | |
# shellcheck disable=SC2120 | |
set_env_path() { | |
local path dir newPath | |
# If we have any args, feed them into ~/.pathrc | |
if (( "${#}" > 0 )); then | |
# shellcheck disable=SC2048 | |
for path in ${*}; do | |
if [[ -d "${path}" ]]; then | |
if ! grep -q "${path}" "${HOME}"/.pathrc; then | |
printf -- '%s\n' "${path}" >> "${HOME}"/.pathrc | |
fi | |
fi | |
done | |
fi | |
# Open an array of potential PATH members, including Solaris bin/sbin paths | |
pathArray=( | |
/usr/gnu/bin /usr/xpg6/bin /usr/xpg4/bin /usr/kerberos/bin \ | |
/usr/kerberos/sbin /bin /sbin /usr/bin /usr/sbin /usr/local/bin \ | |
/usr/local/sbin /usr/local/opt/texinfo/bin /usr/local/opt/libxml2/bin \ | |
/usr/X11/bin /opt/csw/bin /opt/csw/sbin /opt/sfw/bin /opt/sfw/sbin \ | |
/opt/X11/bin /usr/sfw/bin /usr/sfw/sbin /usr/games /usr/local/games \ | |
/snap/bin "${HOME}"/bin "${HOME}"/go/bin /usr/local/go/bin \ | |
"${HOME}"/.cargo /Library/TeX/texbin "${HOME}"/.fzf/bin \ | |
/usr/local/opt/fzf/bin | |
) | |
# If Android Home exists, add more dirs | |
if [[ -d "${HOME}"/Library/Android/sdk ]]; then | |
export ANDROID_HOME="${HOME}"/Library/Android/sdk | |
pathArray+=( "${ANDROID_HOME}"/tools ) | |
pathArray+=( "${ANDROID_HOME}"/tools/bin ) | |
pathArray+=( "${ANDROID_HOME}"/emulator ) | |
pathArray+=( "${ANDROID_HOME}"/platform-tools ) | |
fi | |
# Add anything from .pathrc, /etc/paths and /etc/paths.d/* | |
# i.e. OSX, because path_helper can be slow... | |
while read -r; do | |
pathArray+=( "${REPLY}" ) | |
done < <(cat "$(find "${HOME}"/.pathrc /etc/paths /etc/paths.d -type f 2>/dev/null)" 2>/dev/null) | |
# Iterate through the array and build the newPath variable using found paths | |
newPath= | |
for dir in "${pathArray[@]}"; do | |
# If it's already in newPath, skip on to the next dir | |
case "${newPath}" in | |
(*:${dir}:*|*:${dir}$) continue ;; | |
esac | |
[[ -d "${dir}" ]] && newPath="${newPath}:${dir}" | |
done | |
# Now assign our freshly built newPath variable, removing any leading colon | |
PATH="${newPath#:}" | |
# Finally, export the PATH | |
export PATH | |
} | |
# Run the function to straighten out PATH | |
# shellcheck disable=SC2119 | |
set_env_path |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment