Reputation: 31502
I have:
PATH=/bar:/foo
I want:
PATH=/foo:/bar
I don't want:
PATH=/foo:/bar:foo
So I'm thinking, given the default path is PATH=/bar
, I can modify $path
(which is $PATH
as an associative array):
function prepend_to_path() {
unset $path[(r)$1]
path=($1 $path)
}
prepend_to_path /foo
But that complains with:
prepend_to_path:unset:1: not enough arguments
It's been so long that I don't even remember what (r)
is for, but without it (unset $path[$1]
) I get:
prepend_to_path:1: bad math expression: operand expected at `/home/nerd...'
What am I doing wrong?
Upvotes: 3
Views: 2921
Reputation: 2618
This also works (and is arguably easier to read when you go back to it after a couple of months):
prepend_to_path () {
path[1,0]=$1
typeset -U path
}
typeset -U
will automatically deduplicate the array, keeping only the first occurrence of each element.
Since export
is equivalent to typeset -gx
, you could also export -U path
to kill two birds with one stone.
Edit: typeset -U
needs only to be applied to a particular array once, so one can do that somewhere in one's shell startup and remove the line from the function above.
Upvotes: 2
Reputation: 11090
You can replace the body of your function with:
path=($1 ${(@)path:#$1})
Related answer: https://stackoverflow.com/a/3435429/1107999
Upvotes: 6