How to set environment variables in zsh and bash (macOS and Linux)

2 min read

365 words

It is often advisable to save certain variables, e.g. to be able to call terminal commands more easily. One use case for me was using the AWS CLI. If you create different profiles you have to enter --profile <PROFILE_NAME> for each command if the variable AWS_PROFILE is not set. So for example: aws s3 ls --profile <PROFILE_NAME>. The following article explains how to create these environment variables temporarily (for the current terminal session) but also persistently.

Creating temporary environment variables

Creating a temporary environment variable is easy. To do this, export the desired name, with the desired value:

export VARIABLE_NAME=VARIABLE_VALUE

The value is then saved for the current terminal session.

Persist environment variables

To persist an environment variable you need a .bashrc or a .zshrc. Depending on which shell you use.
Sidenote: Since macOS Catalina uses zsh as the default shell of macOS.

If the required file does not exist, it can be created with the nano editor as follows: nano ~/.zshrc or nano ~/.bashrc. The desired environment variable is then created in the file as with a temporary variable.

The whole thing can also be done in the .bash_profile or .zsh_profile file. I personally use oh-my-zsh so I set my environment variables via .zshrc. The linked article [1] explains the difference between .bash_profile and .bashrc in more detail.

Reinitialize

After making changes in the respective file, you have to reinitialize this file. This can be done by source .bashrc or source .zshrc.

Otherwise you can also restart the terminal window. Because the .bashrc or .zshrc is loaded at every start of the terminal when initializing.

Test if everything works

To check if everything works you can use echo $VARIABLE_NAME. This will return the value of the variable if it is set correctly or an empty result if the variable is not set yet.

➜ ~ export VARIABLE_NAME=VARIABLE_VALUE
➜ ~ echo $VARIABLE_NAME
VARIABLE_VALUE

To get an overview of every single assigned environment variable in the current environment, you can also use the command printenv.

Thanks for reading,
Niklas


  1. Difference .bashrc vs .bash_profile (which one to use?) | GoLinuxCloud ↩︎