pathmunge
is an often-seen function in shell initialization files, used to add entries to the PATH
environment variable without duplication. Examples:
- Fedora
/etc/profile
'spathmunge
. - How can I cleanly add to $PATH? - Unix & Linux
- Unix shell function for adding directories to PATH
I wrote this pathmunge
variation in zsh:
pathmunge() {
local path_array before
# The default is to prepend the argument to PATH
before=1
case $1 in
after)
# Append to PATH
before=
;&
before)
shift
;;
esac
# Split PATH on : into an array
path_array=(${(As.:.)PATH})
# Then remove the arguments from it, since they are to be added in the
# order specified
path_array=(${path_array:|argv})
if [[ -n $before ]]
then
# Reverse the order of the arguments, so that:
# for f in ...; pathmunge f
# and
# pathmunge ...
# have the same effect.
path_array=(${(Oa)argv} $path_array)
else
path_array=($path_array $argv)
fi
# Concatenate the array back to PATH
PATH="${(j.:.)path_array}"
}
Note on implementation: Usually pathmunge
implementations don't add to PATH
if the entry already exists. I took a slightly different path - I'll remove the old instance of entry, and then add the entry as specified. The purpose is to ensure that entries are available in the expected order, since the order matters.
For example, if an entry /foo
has commands shadowing another entry /bar
, and I do pathmunge before /foo
or pathmunge after /foo
with PATH
already containing /foo
and /bar
in some order, I can reasonably expect that now PATH
will have the expected relative order between /foo
and /bar
.
Compatibility with other shells is not a concern. I am fairly competent when it comes to shell scripts. However, I have never made much use of zsh's extensive parameter expansion features. So, I'm looking for pitfalls and performance improvements.