$PATH vs. $path

bashpathzsh

I can't remember why, but a long time ago, I found that for some reason, I needed to set both of these variables. It caused no problems in bash, but now in zsh, when I put

export PATH=~/bin:/opt/local/bin:/opt/local/sbin:$PATH
export path=$PATH

(the same thing I used in .bashrc) in my initialization, I get

/Users/…/.zshenv:export:7: path: inconsistent type for assignment

What do they mean by "type," and what is $path used for?

Best Answer

The error mentioning ‘type’ refers to the data type of the variable, such as string or array.

$PATH is a string, $path is an array. You cannot assign a string, whether by variable or by literal, to a variable typed to contain an array, since the types do not match.

As for what the difference between the two variables are: they are meant to represent the same list of folders, but in different formats. $PATH containing /path/to/one:/path/to/two would mean that $path’s first element is /path/to/one and the second one is /path/to/two.

You shouldn’t need to manage the two variables (and assigning one to the other won’t work since the types do not match) — the shell should handle it for you. Simply append to the $PATH string and the path you add should exist as an element of $path.

This only applies in zsh, inherited from *csh. You can see the ‘binding’ between the two variables with typeset -p PATH.

$path being an array is really convenient:

  • appending and altering the path can be done with array operations like append rather than string manipulation (requiring splitting and joining in the case of editing somewhere in the middle).

  • looping through is just for i ($path) { … } without needing to deal with the setting of the right split character.