Created
April 6, 2025 02:18
-
-
Save Leedehai/1c06277099fb2e29da1ab5541122ad11 to your computer and use it in GitHub Desktop.
Append new item to $PATH only if it doesn't exist already
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
# $PATH and its friends. | |
# If a program is invoked from this terminal, then all environment variables | |
# (including $PATH) are visible to that program. | |
# Use "append_if_new PATH foo/bar" to append path "foo/bar" to $PATH so we avoid | |
# duplication -- if executables with the same name exist in multiple paths | |
# enumerated in $PATH (e.g. caused by "source ~/.zshrc" multiple times), then | |
# the first find wins anyway. | |
append_if_new() { | |
local variable_name="$1" | |
local new_item="$2" | |
# Get the current value of the environment variable. This "(P)" takes the | |
# value string this variable name refers to, not the name string itself. | |
# The equivalence of "(P)" in Bash scripts is "!". | |
local variable_value="${(P)variable_name}" | |
# Add the new item only if it doesn't already exist | |
if [[ ":$variable_value:" != *":$new_item:"* ]]; then | |
if [[ -z "$variable_value" ]]; then | |
export "$variable_name"="$new_item" | |
else | |
export "$variable_name"="$variable_value:$new_item" | |
fi | |
fi | |
} | |
append_if_new PATH "$HOME/.cargo/bin" # Rust |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment