How to add permanent environment variable in zsh

Bash

Since Bash is typically the default shell you can open up this file in your home directory:

$ vim ~/.bash_profile

And add your variable to this file:

export ENV_VAR=12345

You can do this without even having to edit this file if you like, using the following one-liner:

$ echo 'export ENV_VAR=12345' >> ~/.bash_profile

And then confirm like so:

$ cat ~/.bash_profile
for i in ~/.bash_profile.d/[0-9]*; do
  . "$i"
done
export ENV_VAR=12345

After doing the above, if you open a new terminal you should see that environment variable has been set:

$ echo $ENV_VAR
12345

Zsh

If you find that you're using an alternative shell such as zsh, that uses a different set of configuration files maintained within your home directory, ~. Luckily the syntax of the changes is basically the same, just different files. So you can add the above example to this file instead:

$ echo 'export ENV_VAR=12345' >> ~/.zshenv

And then when you launch a zsh:

$ echo $ENV_VAR
12345

References

  • Zsh Startup Files

First, execute in a terminal with zsh (Z Shell):

echo 'export ENV_VAR=12345' >> ~/.zshenv

Then, reload changes:

source ~/.zshenv

Finally, test if your new variable is set:

echo $ENV_VAR

Note: By standard, the .zshenv file should only contain environment variables setting commands. .zshenv is sourced on all invocations of the shell, hence it will persist even after you restart your machine.