Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: Correct way to set environment



On Dec 15,  2:29pm, Florian Lindner wrote:
}
} I've ushed .zshenv for that purpose since it is sourced on every shell
} invocation.

So far so good.

} No other relevant z-files are present. This works as far as it sets
} the PYTHONPATH variable but if I launch python it is not taken into
} account. When I use export PYTHONPATH, the pythonpath gets longer and
} longer if I invoke a zsh session within a zsh session.

You do need to export any variable that you want passed down to child
processes of the shell, such as the python interpreter.  PATH is one
of the variables exported by default, but PYTHONPATH is not.

I think you'll note that PATH is similarly getting longer every time.

The solution to this is to test whether the value already contains the
substring you're going to add, and skip the assignment if it would be
redundant.  You can do this yourself --

    export PYTHONPATH
    if [[ $PYTHONPATH != $HOME/flof/src:* ]];
    then PYTHONPATH=$HOME/flof/src:$PYTHONPATH
    fi

-- or you can let zsh do it by declaring the variable to be an array
containing unique values.

At startup, zsh "ties" the array variable $path to the environment string
$PATH.   If you run

    print $path
    print $PATH

you should see strings that are identical except that the first one has
spaces where the second has colons.  (If instead you see only the first
element of $PATH when printing $path, you have the ksharrays option set,
and must use ${path[@]} instead.)

With this connection, anything assigned to path is copied to PATH and
vice-versa, so now you can do:

    path=(~/flof/src $path)

You can set up a similar equivalence yourself with the typeset command:

    typeset -T PYTHONPATH pythonpath
    pythonpath=(~/flof/src $pythonpath)

With this is place, you can declare the array values to be unique:

    typeset -U path pythonpath

Zsh then collapses duplicates out of the arrays and updates the "tied"
strings to match.  Note, however, that if you assign directly to the
string variable instead of assigning to the array, then zsh does NOT
apply the uniqueness property, so you must remember to use the array
assignment form after tying.

There is one exception to the above:  If you combine creating the "tie"
along with the assignment into a single command, the uniqueness property
applies.

    typeset -UTx PYTHONPATH=$HOME/flof/src:$PYTHONPATH pythonpath

You can also use

    export -UT PYTHONPATH=$HOME/flof/src:$PYTHONPATH pythonpath

if you think that reads better.

This doesn't work for $path because it's already "special", so you must
fix that one up in two steps.

    path=(~/flof/src $path)
    typeset -U path

Enjoy.



Messages sorted by: Reverse Date, Date, Thread, Author