Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Is there an easy way in zsh to add a directory to my PATH only if it's not already present? (or, more generally, any environment variable). I've tried:

PATH+=/my/directory

... but if that's executed twice, it gets added twice.

share|improve this question
2  
@uther, that's not a duplicate since that other question was for bash, while this one is for zsh which has its own very way to address this issue. –  Stephane Chazelas Jan 25 '13 at 21:41
add comment

3 Answers

up vote 13 down vote accepted

In zsh $PATH is tied (see typeset -T) to the $path array. You can force that array to have unique values with:

typeset -U path

And then, add the path with:

path+=(~/foo)

Without having to worry if it was there already.

To add it at the front, do:

path=(~/foo "$path[@]")

if ~/foo was already in $path that will move it to the front.

share|improve this answer
    
Don't you mean typeset -Ug path? When I use typeset -U path in my ~/.zshrc file, I always get back an error about nothing being in the path while the zshrc is running –  eMxyzptlk Oct 7 '13 at 22:31
    
@eMxyzptlk, strange. -g is to avoid restricting the scope, but in ~/.zshrc, the scope is global already. Also, I've never seen zsh complain about an empty $PATH (except for the command not found errors of course). –  Stephane Chazelas Oct 8 '13 at 6:55
add comment

Add export -U PATH=~/foo${PATH:+:$PATH} to one of your startup files. The -U keeps only the first occurrence of a value in arrays or certain : delimited variables like PATH.

share|improve this answer
    
Note though that if $PATH was initially empty or unset, you're adding both ~/foo and the current directory (through the empty string) to $PATH. –  Stephane Chazelas Jan 26 '13 at 9:31
add comment

You'll have to do something like:

if echo $PATH | grep :newpath: ; then doIfPresent; else doIfMissing; fi

This works only if newpath is delimited bu two ':', need to consider the cases when it is at the beginning or end similarly.

Urgh.

share|improve this answer
1  
You can do that inside the shell, with only Bourne/POSIX features. This avoids quoting headaches (at least make that echo "$PATH": always put double quotes around variable substitutions). case ":$PATH:" in *:/new/directory:*) :;; *) PATH=$PATH:/new/directory;; esac –  Gilles Jan 26 '13 at 0:52
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.