Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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:


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

share|improve this question
@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. – Stéphane Chazelas Jan 25 '13 at 21:41
up vote 23 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:


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 – kalbasit 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). – Stéphane Chazelas Oct 8 '13 at 6:55

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

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.


share|improve this answer
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

Your Answer


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.