Flash Sale:75% Off Hosting + Free DomainEnds in13h47m14sView Plans
Hostvento logoHostvento

How to Set Environment Variables in Zsh

Set a variable for the current session, or keep it permanently in ~/.zshrc.

How-To Guides1 min read5 screenshots

Set a variable temporarily

A variable set this way exists only in the current terminal session.

export MY_VAR="value"

Example with a database address:

export DatabaseURL="mysql://user:password@localhost:3306/mydatabase"
Setting an environment variable in Zsh

Do not put spaces around =.

Check it:

echo $DatabaseURL
Confirming the environment variable
Warning: Do not store real passwords in shell history or startup files that others can read. Keep secrets in a file with chmod 600 or in a secrets manager.

Set a variable permanently

Step 1: Open the .zshrc file

nano ~/.zshrc

(The file name is lower case, .zshrc.)

Step 2: Add the variable

export USER_NAME="Anna"
Adding the variable to the .zshrc file

Save and exit.

Step 3: Apply the change

source ~/.zshrc
Reloading the .zshrc file

Step 4: Check it

echo $USER_NAME
Verifying the environment variable

Other Zsh startup files

  • ~/.zshenv is read by every Zsh, even in scripts. Good for PATH and variables that all programs need.
  • ~/.zprofile is read by login shells.
  • ~/.zshrc is read by interactive shells.
  • /etc/zshenv sets variables for all users.

Useful commands

Show all variables:

printenv

Remove a variable:

unset USER_NAME

Add a folder to the PATH:

export PATH="$PATH:$HOME/bin"

Quick recap

  • export NAME="value" for the session.
  • Add the line to ~/.zshrc and run source ~/.zshrc to keep it.