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:
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
.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
.bashrc in more detail.
After making changes in the respective file, you have to reinitialize this file. This can be done by
source .bashrc or
Otherwise you can also restart the terminal window. Because the
.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
Thanks for reading,