Setting Env Variables in Windows, Linux & MacOS: Beginner’s Guide

What Are Environment Variables? 

Environment variables are key-value pairs used by the operating system to configure settings and manage the environment for applications running on a computer. These variables influence the behavior of software without changing its source code. They store system-wide values such as directory paths, system settings, or application configurations, allowing applications to function in various environments without modification.

Typically prefixed with names (e.g., PATH, HOME), environment variables are adjusted at different levels like the user or system level, making them versatile for software deployment. They are integral to scripts and batch processes that automate tasks. 

Developers and system administrators widely use these variables to reduce configuration errors and improve the adaptability of systems across environments.

The Importance of Environment Variables in System Configuration 

Environment variables aid in system configuration by providing a centralized way to manage settings that affect applications and services. They eliminate the need to hardcode values in scripts or programs, making software deployment more flexible and maintainable.

One key benefit is portability. By defining environment variables, applications can run across different environments—development, testing, and production—without requiring code changes. This ensures consistency and reduces the risk of misconfigurations.

Security is another advantage. Sensitive information such as API keys, database credentials, and authentication tokens can be stored as environment variables instead of being embedded in source code, reducing exposure risks.

Additionally, environment variables enable automation. System administrators and DevOps teams use them in scripts, cron jobs, and configuration management tools to dynamically adjust system settings, making processes more efficient and scalable.

Common Environment Variables and Their Uses 

Several environment variables are commonly used across operating systems to manage system behavior and application configurations:

  • PATH: Defines directories where executable files are located, allowing commands to be run without specifying full file paths.
  • HOME (Linux/macOS) / USERPROFILE (Windows): Specifies the current user’s home directory, where user-specific configuration files are stored.
  • SHELL: Indicates the default command-line shell (e.g., /bin/bash, /bin/zsh).
  • TEMP / TMP: Points to directories used for storing temporary files.
  • LANG: Sets the system’s language and locale preferences.
  • PWD: Represents the present working directory in a shell session.
  • USER / USERNAME: Holds the name of the currently logged-in user.

By understanding and leveraging these variables, users can configure their systems, automate workflows, and improve security practices.

Tips From the Expert

In my experience, here are tips that can help you better manage environment variables effectively across diverse systems and deployment environments:

  1. Use directory-specific .env files for modular configurations: For large applications, consider splitting environment variables into multiple .env files specific to different services, modules, or microservices (e.g., .env.database, .env.cache). This helps isolate concerns, improves maintainability, and simplifies debugging when a specific service behaves unexpectedly.
  2. Limit environment variable exposure to child processes: Avoid exporting all environment variables globally unless necessary. Instead, export only specific variables to child processes using shell commands or application-level scoping. This minimizes the risk of sensitive data leaks when running scripts or external processes.
  3. Rotate sensitive environment variables regularly: Frequently rotate secrets and sensitive variables such as API keys, database passwords, and access tokens. Automate this process using CI/CD pipelines or secret management tools, and ensure the application can handle seamless variable updates during runtime or deployment.
  4. Avoid setting global variables in system-wide files unless necessary: System-wide configuration files (like /etc/environment) affect all users and services, potentially introducing conflicts. Use user-specific files (e.g., ~/.bashrc) whenever possible, and reserve global settings for variables that truly need to be available across the entire system.
  5. Use container-specific environment variable management: In containerized environments (e.g., Docker or Kubernetes), prefer defining environment variables via container orchestrators rather than embedding them within the container images or .env files. This improves security and allows for centralized control over configurations.
Ran Cohen photo
Ran Cohen
CTO & Co-Founder, Configu
Before co-founding Configu, Ran was a full stack developer at Testim.io and previously served in an elite cybersecurity unit in the Israeli Defense Forces.

How to Set Environment Variable in Windows 

Environment variables in Windows can be set using different methods, including the graphical user interface (GUI) and the command line. Below are step-by-step instructions for each method.

Checking Existing Environment Variables

Before setting a new environment variable, consider checking the existing ones.

Using Command Prompt:

To list all environment variables, run:

set

To check a variable, use:

echo %VARIABLE_NAME%

Using PowerShell:

To list all environment variables, use:

Get-ChildItem Env:

To check a variable, use:

echo $Env:VARIABLE_NAME

Setting an Environment Variable Using the GUI

To configure a variable using the GUI:

  1. Press Windows + R to open the Run prompt.
  1. Type sysdm.cpl and click OK.
  1. In the System Properties window, navigate to the Advanced tab.
  1. Click the Environment Variables button.
  1. In the Environment Variables window, choose between User variables (for the current user only) and System variables (for all users).
  1. Click New…, enter the variable name and value, and click OK.

Setting an Environment Variable Using Command Prompt

To create a user-specific environment variable, use:

setx VARIABLE_NAME "Variable Value"

Example:

setx MY_ENV_VAR "Hello World"

To set a system-wide environment variable (requires administrator privileges), use:

setx VARIABLE_NAME "Variable Value" /M

Example:

setx MY_GLOBAL_VAR "Global Value" /M

Note: Changes take effect in new Command Prompt sessions. Restart the terminal or log out and back in to apply them.

Unsetting an Environment Variable

Using the GUI:

  1. Open the Environment Variables window (as described earlier).
  2. Select the variable you want to remove.
  1. Click Delete and confirm.

Using the registry (advanced users only):

To remove a user-specific variable, run:

reg delete HKEY_CURRENT_USER\Environment /v VARIABLE_NAME /f

To remove a system-wide variable, run:

reg delete "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v VARIABLE_NAME /f

Example:

reg delete HKEY_CURRENT_USER\Environment /v MY_ENV_VAR /f

Using environment variables simplifies configuration, improves portability, and improves security by keeping sensitive values out of source code.

How to Set an Environment Variable in Linux 

Environment variables in Linux are key-value pairs used to configure system settings and control application behavior. Developers can set them temporarily for the current session or persistently to be available across reboots.

Checking Current Environment Variables

To list all environment variables in the current session, use:

env

To check the value of a variable, use either:

printenv VARIABLE_NAME

Or

echo $VARIABLE_NAME

Example:

echo $SHELL

/bin/bash

Setting an Environment Variable (Temporary)

To set an environment variable for the current session, use:

export VARIABLE_NAME="variable value"

Example:

export JAVA_HOME="/usr/bin/java"

Verify the variable is set by running:

echo $JAVA_HOME

Note: This variable will be available only for the current session. If you open a new terminal, it will not persist.

Making an Environment Variable Persistent

To keep the variable after restarting the system, add it to the ~/.bashrc file (for a single user):

  1. Open the file in a text editor:
vi ~/.bashrc
  1. Add the export command at the end of the file:
export JAVA_HOME="/usr/bin/java"
  1. Apply the changes:
source ~/.bashrc

Now, the environment variable will persist across sessions.

Creating a Global Environment Variable

To set an environment variable for all users, add it to system-wide configuration files.

  1. Open the /etc/environment file:
sudo vi /etc/environment
  1. Add the variable without using export:
GLOBAL_VARIABLE="This is a global variable"
  1. Apply the changes:
source /etc/environment
  1. Alternatively, you can define global variables in /etc/profile using export:
export GLOBAL_VARIABLE="/usr/local/development"
  1. To test, switch users and check if the variable is accessible:
su - another_user

echo $GLOBAL_VARIABLE

This method ensures the variable is available for all users and persists after system reboots.

How to Set Environment Variables in MacOS 

Environment variables in macOS help configure system settings and control application behavior. They can be set temporarily for the current session or permanently to persist across reboots.

Checking Current Environment Variables

To list all environment variables, use:

printenv

To display a variable’s value, use:

echo $VARIABLE_NAME

Example:

echo $PATH

This prints the directories where executable files are located.

Setting a Temporary Environment Variable

To set an environment variable for the current terminal session, use:

export VARIABLE_NAME="value"

Example:

export MY_VAR="Hello macOS"

To verify, run:

echo $MY_VAR

Note: This variable will be lost once you close the terminal.

Setting a Permanent Environment Variable

To make an environment variable persistent, add it to the ~/.bash_profile file (for Bash users) or ~/.zshrc (for Zsh users, the default shell in macOS Catalina and later).

  1. Open the file in a text editor:
nano ~/.bash_profile  # For Bash users

nano ~/.zshrc         # For Zsh users
  1. Add the export command at the end of the file:
export VARIABLE_NAME="value"
  1. Save the file (CTRL + X, then Y, then Enter).
  1. Apply the changes:
source ~/.bash_profile  # For Bash users

source ~/.zshrc         # For Zsh users
  1. Now, the variable will persist across terminal sessions.

Adding to an Existing Environment Variable

You can append a value to an existing variable, such as PATH:

export PATH=/Users/test/custom_folder:$PATH

This ensures the new directory is included when searching for executable files.

Unsetting an Environment Variable

To remove an environment variable, use:

unset VARIABLE_NAME

Example:

unset MY_VAR

This removes the variable for the current session. If the variable was set permanently, remove it from ~/.bash_profile or ~/.zshrc and reload the file with source.

Related content: Read our guide to testing environment

5 Best Practices for Managing Environment Variables 

Here are some useful practices to keep in mind when working with .env variables.

1. Keep Sensitive Data Secure

Environment variables can include sensitive data like API keys or passwords. Avoid exposing sensitive environment variables in source code or public repositories. Use permission-based access to restrict who can view or modify crucial variables, ensuring sensitive data remains confidential.

Use tools like secret managers or encrypted storage systems to manage sensitive information securely. By implementing tight security protocols, organizations can reduce the risk of data leaks or unauthorized access, maintaining a strong environment security posture critical for protecting sensitive information.

2. Use Consistent Naming Conventions

Adopting consistent naming conventions for environment variables improves readability and manageability. Use clear and descriptive names, often in uppercase separated by underscores, such as DATABASE_URL or API_KEY. This practice minimizes confusion and promotes clarity when editing or reviewing variable settings.

Clear conventions also enable collaboration within teams, making it easier to onboard new members and maintain documentation. By standardizing naming schemas, organizations improve the ease of debugging and troubleshooting, which contributes to a cohesive and simplified development process and environment management.

3. Document Environment Variable Usage

Thoroughly documenting environment variable usage is essential for maintaining a clear understanding across team members and future onboarding. Record each variable’s purpose, default values, data types, and any constraints or requirements, ensuring complete comprehension of its role within the system.

Proper documentation mitigates the risk of misconfiguration by providing clear guidelines and contexts for each variable, improving communication and operational efficiency. This transparency supports collaboration and allows for smoother transitions during staff changes or project handovers.

4. Avoid Hardcoding Values in Code

Hardcoding values within source code reduces flexibility and increases maintenance complexity. By using environment variables instead, configurations become easy to change without touching the codebase. This practice improves portability and scalability, especially across different deployment environments or systems.

Replacing hardcoded values with environment variables also improves security and modularity by separating code logic from configuration data. This separation simplifies the adaptation of applications to new conditions or environments, reinforcing the software’s resiliency in dynamic operating contexts.

5. Use .env Files Where Applicable

The use of .env files for storing environment variables is a best practice for managing configuration settings in development environments. This file should remain local and uncommitted to version control systems to protect sensitive information. Tools like dotenv or Configu can automatically load these settings into the environment, simplifying setup processes.

.env files provide an organized structure for managing environment-specific settings, fostering maintainability and ease of development. Proper use of these files allows for seamless transitions between environments during deployment, ensuring applications receive consistent configurations in various operational contexts.

Managing and Securely Storing Environment Variables with Configu

Configu is a configuration management platform comprised of two main components, the stand-alone Orchestrator, which is open source, and the Cloud, which is a SaaS solution:

Configu Orchestrator

As applications become more dynamic and distributed in microservices architectures, configurations are getting more fragmented. They are saved as raw text that is spread across multiple stores, databases, files, git repositories, and third-party tools (a typical company will have five to ten different stores).

The Configu Orchestrator, which is open-source software, is a powerful standalone tool designed to address this challenge by providing configuration orchestration along with Configuration-as-Code (CaC) approach.

Configu Cloud

Configu Cloud is the most innovative store purpose-built for configurations, including environment variables, secrets, and feature flags. It is built based on the Configu configuration-as-code (CaC) approach and can model configurations and wrap them with unique layers, providing collaboration capabilities, visibility into configuration workflows, and security and compliance standardization.

Unlike legacy tools, which treat configurations as unstructured data or key-value pairs, Configu is leading the way with a Configuration-as-Code approach. By modeling configurations, they are treated as first-class citizens in the developers’ code. This makes our solution more robust and reliable and also enables Configu to provide more capabilities, such as visualization, a testing framework, and security abilities.

Learn more about Configu

Configu Editorial Team

The Configu Editorial Team is dedicated to delivering high-quality insights on configuration management, DevOps, software engineering, and security. Our team of writers, engineers, and industry experts collaborates to provide in-depth articles, guides, and research-backed content to help developers and organizations prevent misconfigurations and streamline their workflows.

Related Content

Env in PHP: The Basics and a Quick Tutorial

Working with GitLab Environment Variables: Step-by-Step

Setting Environment Variables in PowerShell: A Practical Guide

React Environment Variables: Basics, Tutorial, and Best Practices

Working with Python Configuration Files: Tutorial & Best Practices

Jenkins Environment Variables: Practical Guide with Code Examples

Working with Java Environment Variables & 4 Ways to Set Variables

7 Types of Testing Environments and Best Practices for Yours

4 Ways to Set Docker Compose Environment Variables

How to Use Github Actions Environment Variables

Next.js Environment Variables: Built-In, Public, and Private

Node.js Environment Variables: Working with process.env and dotenv

Environment Variables: How to Use Them and 4 Critical Best Practices

Setting Docker Environment Variables: The Ultimate Guide

Leveraging Environment Variables in Python Programming

Try Configu for free
Painless end-to-end configuration management platform
Get Started for Free