2 minute read

This post explains how to set and read environment variables.

What Are Environment Variables?

In the world of computing, environment variables serve as dynamic placeholders that various applications and processes use to store critical information. These can range from defining system-wide flags to specifying the paths where essential files and programs are located. A widely recognized example is the PATH variable, which instructs your operating system on where to find executable programs.

Listing All Environment Variables

If you’re curious about all the environment variables currently in play on your system, you can unveil the full list with a simple command:

% printenv

This command will provide a comprehensive overview of the environment variables, their names, and their corresponding values.

Retrieving the Value of a Single Environment Variable

To retrieve the value of a specific environment variable, utilize the echo command, followed by the variable’s name enclosed within dollar signs. Here’s an example using the SHELL variable:

% echo $[variable name]

Replace [variable name] with the name of the variable you’re interested in.

% echo $SHELL
/bin/zsh

Setting the Value of an Environment Variable (Within Session)

When you need to set the value of an environment variable for the duration of your current terminal session, use the export command. Simply specify the variable name and your desired value, like so:

% export [variable_name]=[variable_value]

Replace [variable name] with the name of your choice and [variable value] with your preferred value.

% export my_var=my_value
% echo $my_var
my_value

Clearing an Environment Variable

To remove an environment variable from your current session, use the unset command followed by the variable name:

Copy code
unset [variable_name]

Replace [variable name] with the name of the variable you wish to clear.

Setting an Environment Variable Permanently

For those who want to make their environment variable changes permanent, the process differs based on your shell. Here are the steps for two popular shells:

For Zsh Users:

  1. Open and edit your ~/.zshrc file.
  2. Insert the export statement within the file.
  3. Keep in mind that these changes won’t take effect until you either launch a new terminal session or source the file:
    source ~/.zshrc
    

For Bash Users:

  1. Open and edit your ~/.bash_profile file.
  2. Insert the export statement within the file.
  3. Similar to Zsh, the changes will only become permanent after you launch a new terminal session or source the file:
    source ~/.bash_profile
    

Identifying Your Current Shell

To determine which shell you are currently using, run the following command:

Copy code
echo $0

This command will display the name of your active shell, such as -zsh or -bash.

Tags:

Categories:

Updated: