ZSH: Where to place environment variable so that launched application can pick it up

command lineenvironment-variableslaunchershellzsh

I need an environment variable KEY="value" made available to a GUI application before starting it. The launcher file (the one that places the icon on the desktop and sidebar in Ubuntu) has a value of Exec=/path/to/executable/file.

When using ZSH, where should I define this variable so that it is available to that application whether I click the application launcher or whether I directly type /path/to/executable/file in my shell?

In my command line prompt, I tried typing both KEY="value" and export KEY="value" before clicking the launcher, but it didn't seem to work. I also tried both of those lines in my ~/.zshrc, did a source ~/.zshrc from my shell then clicked the launcher again, but that also didn't work.

Which file should it go in? I believe have a choice of ~/.zshenv, ~/.zprofile, ~/.zshrc, and ~/.zlogin.

(For bonus points, should I use export or not?)

(Am I required to at least log out and log back in, before the variable becomes available to the application when it's launched from the launcher?)

Best Answer

As you want the variable to be defined as well in your terminal shells (interactive non-login shell) and for the desktop launcher icons (X-server started by non-interactive login shell) you should put the definition in your ~/.zshenv.

And yes, you have to restart your x-session in order to have the new environment available for your desktop icons. Imagine such a startup scheme: Graphical Login -> Use your default shell to start the X session -> Desktop -> Shell terminal / Launch program via icon, so the child shells inherit the environment from the parent, which is used to start the X session. That shell read the RC-files only once -- on your login to the X session.

For the bonus point. This is what the manual says:

export [ name[=value] ... ] The specified names are marked for automatic export to the environment of subsequently executed commands. (...)

If you define your variable in ~/.zshenv, you can in principle omit the export as this file is read in by default. The only difference arises if you start a shell with zsh -f, which sources no RC files. A little demonstration:

% foo=foo_defined
% export bar=bar_defined
% print -l $foo $bar
foo_defined
bar_defined
% zsh -f
% print -l $foo $bar
bar_defined
% 

I. e. only the exported $bar is defined in subsequent shells. But to be on the safe side, use export -- I can't think of a case where this is harmful.

Related Question