4

As I start to migrate from bash to zsh, I'm finding many differences. One of them is the following:

envy% echo $path
/usr/local/bin /usr/bin /bin /usr/sbin /sbin /opt/X11/bin

envy% echo $PATH
/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin

Why do these mirror each other except for the spaces and colons and when you modify them? What's the understanding about zsh environment variables that I don't have here?

1 Answer 1

9

$PATH ist a scalar variable, whereas $path is an array.

Notice that in the first case the directories are delimited by colons inside the $PATH string itself; in the second case the array is automatically expanded and separated by spaces:

$ print $PATH
/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin
$print $path
/bin /usr/bin /usr/local/bin /usr/X11R6/bin

Both variants are automatically kept in sync by zsh. So, what's the benefit of using a array?

  • The latter you can declare via typeset -U path to "keep only the first occurrence of each duplicated value" (from man zshbuiltins). That means this keeps your path clean, even if you successively source your ~/.zshrc (because you changed it or whatever) and do not clutter it up with the same values again and again.
  • You can use path+=(/new/path) to add a new directory to your PATH. To remove an element you have to use some tricks, see e.g. https://stackoverflow.com/q/3435355/2037712 or http://www.zsh.org/mla/users//2005/msg01132.html
  • You can easily loop over the elements in the PATH via for i ($path) { print $i # or do something else }

Finally, here is an excerpt from my config with my attempt to keep my search path tidy:

typeset -U path
path=(/new/path1
      /new/path2
      $path)
export PATH

Source: My own answer to another question.

1
  • Brilliant. Thank you.
    – Roxy
    Commented Jun 12, 2019 at 17:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .