How to Display Environment Variables

Terminal showing commands and output for displaying environment variables: 'env', 'printenv', and 'set' examples, highlighted key variables like PATH HOME, USER, custom variables.

How to Display Environment Variables

Why Understanding Environment Variables Matters in Your Development Journey

Environment variables form the backbone of modern software configuration, yet they remain one of the most misunderstood aspects of development work. Whether you're deploying your first application or managing complex production systems, knowing how to properly display and manage these variables can mean the difference between smooth operations and hours of frustrating debugging. These hidden configuration values control everything from database connections to API keys, and understanding them is essential for any developer, system administrator, or DevOps professional.

At their core, environment variables are dynamic values that affect the behavior of running processes on your computer or server. They exist outside your code, providing a flexible way to configure applications without hardcoding sensitive information or system-specific settings. This separation of configuration from code follows the twelve-factor app methodology and represents a fundamental best practice in modern software development.

Throughout this comprehensive guide, you'll discover multiple methods for displaying environment variables across different operating systems and contexts. You'll learn practical commands, understand security implications, explore best practices for managing these variables, and gain insights into troubleshooting common issues. Whether you work with Windows, macOS, Linux, or containerized environments, you'll find actionable techniques that you can implement immediately in your workflow.

Understanding the Fundamentals of Environment Variables

Before diving into specific commands and techniques, it's crucial to grasp what environment variables actually represent in your system's ecosystem. These variables serve as a communication mechanism between your operating system and the applications running on it. When a program starts, it inherits a set of environment variables from its parent process, creating a chain of configuration that flows through your entire system.

Environment variables typically consist of key-value pairs, where the key is the variable name (usually in uppercase by convention) and the value is the data it contains. Common examples include PATH, which tells your system where to find executable programs, HOME, which points to your user directory, and USER, which contains your username. Applications also create their own environment variables for configuration purposes, such as DATABASE_URL for database connections or API_KEY for authentication credentials.

"The ability to externalize configuration through environment variables transforms rigid applications into flexible, portable systems that can adapt to any environment without code changes."

The Scope and Lifecycle of Environment Variables

Environment variables exist at different scopes within your system. System-wide variables are available to all users and processes on the machine, while user-specific variables are only accessible to a particular user account. Additionally, session variables exist only for the duration of a terminal session or process, disappearing when you close the window or the program terminates.

Understanding these scopes is critical when deciding where to set variables and how to display them. A variable set in your current terminal session won't appear in other windows or persist after you log out. Conversely, system-wide variables require administrative privileges to modify but provide consistent configuration across your entire system. This hierarchy allows for flexible configuration management, where you can override system defaults with user preferences and temporarily adjust settings for specific tasks.

Displaying Environment Variables on Windows Systems

Windows provides several methods for viewing environment variables, each suited to different scenarios and user preferences. The graphical interface offers an intuitive approach for occasional viewing and editing, while command-line tools provide scriptable, automation-friendly alternatives.

Using the Windows GUI Environment Variables Editor

The traditional Windows approach involves accessing the System Properties dialog. You can reach this by right-clicking "This PC" or "My Computer," selecting Properties, then clicking "Advanced system settings," and finally clicking the "Environment Variables" button. This interface displays both user variables and system variables in separate sections, allowing you to view, add, edit, or delete variables through a familiar dialog-based interface.

This graphical method works well for quick checks and simple edits, but it becomes cumbersome when you need to review many variables or incorporate environment variable inspection into automated workflows. The interface also doesn't provide easy ways to copy variable values or search through large lists of variables.

Command Prompt Methods for Displaying Variables

The Command Prompt offers several commands for displaying environment variables with varying levels of detail and filtering capabilities:

  • ๐Ÿ” set - Displays all environment variables and their values
  • ๐Ÿ” set VARIABLE_NAME - Shows only variables that start with the specified name
  • ๐Ÿ” echo %VARIABLE_NAME% - Displays the value of a specific variable

The basic set command without arguments produces a comprehensive list of all environment variables in the current session. This output includes both system variables and any variables set specifically for the current command prompt window. The format displays each variable as NAME=VALUE, making it easy to read and parse.

When you need to find specific variables, the set command accepts a prefix parameter. For example, set PATH displays all variables beginning with "PATH", which typically includes PATH itself along with related variables like PATHEXT. This filtering capability proves invaluable when working with systems that have dozens or hundreds of environment variables.

PowerShell Approaches for Environment Variable Display

PowerShell provides more sophisticated options for viewing and manipulating environment variables, treating them as objects rather than simple text strings. The primary methods include:

Command Purpose Output Format
Get-ChildItem Env: Lists all environment variables Table with Name and Value columns
$env:VARIABLE_NAME Displays specific variable value Plain text value
Get-Item Env:VARIABLE_NAME Retrieves specific variable object Object with properties
[Environment]::GetEnvironmentVariable() Gets variable from specific scope String value

The Get-ChildItem Env: command treats the environment as a drive, allowing you to navigate and query it using familiar PowerShell cmdlets. This approach enables powerful filtering and sorting operations. For example, you can sort variables alphabetically, filter by value content, or export the entire environment to a file for documentation or comparison purposes.

"PowerShell's object-oriented approach to environment variables enables sophisticated filtering, sorting, and manipulation that goes far beyond simple text processing."

The direct variable access syntax $env:VARIABLE_NAME provides the quickest way to check a single variable's value. This method integrates seamlessly with PowerShell scripts, allowing you to use environment variable values in conditional logic, string concatenation, and other operations without additional parsing.

Displaying Environment Variables on Unix-Based Systems

Linux, macOS, and other Unix-like systems share common approaches to environment variables, though some platform-specific variations exist. These systems typically use shell environments like Bash, Zsh, or Fish, each with its own syntax and features for variable management.

Basic Shell Commands for Variable Display

The most straightforward commands for viewing environment variables in Unix-based systems include:

  • ๐Ÿ’ป printenv - Displays all environment variables or a specific variable
  • ๐Ÿ’ป env - Shows the current environment or runs a command with a modified environment
  • ๐Ÿ’ป echo $VARIABLE_NAME - Prints the value of a specific variable
  • ๐Ÿ’ป set - Displays all shell variables and functions (Bash)
  • ๐Ÿ’ป export - Shows exported environment variables (when used without arguments)

The printenv command offers the cleanest output for viewing environment variables. Without arguments, it lists all variables in NAME=VALUE format. With a variable name as an argument, it prints only that variable's value, making it ideal for scripts that need to capture specific configuration values. Unlike some alternatives, printenv focuses exclusively on environment variables, excluding shell-specific variables and functions.

The env command serves dual purposes. Without arguments, it displays the current environment similarly to printenv. However, its primary purpose is running commands with a modified environment, making it invaluable for testing how applications behave with different configurations. For example, env DATABASE_URL=test://localhost myapp runs "myapp" with a temporary DATABASE_URL setting that doesn't affect your current shell.

Advanced Filtering and Formatting Techniques

Unix systems excel at text processing, and you can combine environment variable commands with standard Unix tools to create powerful queries. These techniques leverage pipes and filters to extract exactly the information you need from potentially hundreds of variables.

To find variables containing specific text in their names, use grep with printenv: printenv | grep -i "path" displays all variables with "path" in their name (case-insensitive). For more complex filtering, you might search for variables with specific value patterns: printenv | grep "\/usr" shows all variables containing "/usr" in their values, helping you identify system path configurations.

Sorting variables alphabetically improves readability when reviewing long lists: printenv | sort produces an ordered list. For variables with multi-line values or complex content, you can use awk or sed to format the output. For instance, printenv | awk -F= '{printf "%-30s %s\n", $1, $2}' creates a neatly aligned two-column display with variable names in the first column and values in the second.

"The Unix philosophy of combining simple tools through pipes transforms basic environment variable commands into sophisticated inspection and analysis systems."

Shell-Specific Variable Display Methods

Different shells offer unique approaches to displaying variables. In Bash, the declare -p command shows variables with their attributes and exact values, including special characters that might be hidden in normal output. This proves particularly useful when debugging quoting issues or unexpected variable behavior.

Zsh users can leverage the typeset command, which provides similar functionality to Bash's declare. Additionally, Zsh's associative arrays and advanced parameter expansion features offer sophisticated ways to manipulate and display environment data. The command print -l ${(k)parameters} lists all parameter names, while print -l ${(kv)parameters} shows both names and values.

Fish shell takes a different approach with its set --show VARIABLE_NAME command, which displays not just the value but also the scope and export status of variables. This detailed information helps understand exactly where a variable is defined and how it will be inherited by child processes.

Displaying Variables in Development Environments and Containers

Modern development workflows increasingly rely on containerization, virtual environments, and integrated development environments (IDEs). Each of these contexts requires specific approaches to viewing environment variables, as they often create isolated environments with their own variable sets.

Docker and Container Environments

Docker containers run with their own isolated environment, separate from the host system. To view environment variables inside a running container, you need to execute commands within the container's context. The primary method uses docker exec: docker exec container_name printenv displays all environment variables in the specified container.

For containers that aren't currently running, you can inspect the environment variables defined in the image or container configuration using docker inspect. This command outputs detailed JSON information about the container, including its environment: docker inspect container_name | grep -A 20 "Env" extracts the environment section from the inspection output.

When building Docker images, the Dockerfile's ENV instructions set environment variables. You can view these by examining the Dockerfile itself or by running a container from the image and checking its environment. Docker Compose files also define environment variables through the environment key or env_file directive, and you can verify these settings by inspecting the running services or checking the compose file directly.

Python Virtual Environments and Application Contexts

Python applications running in virtual environments inherit the system's environment variables but can also define their own through various mechanisms. Within a Python script or interactive session, you can display environment variables using the os module:

Python Method Description Example
os.environ Dictionary of all environment variables print(os.environ)
os.environ.get() Retrieves specific variable with optional default os.environ.get('HOME', '/default')
os.getenv() Alternative method for getting variable os.getenv('PATH')
dict(os.environ) Creates a regular dictionary from environment env_dict = dict(os.environ)

Many Python projects use .env files managed by libraries like python-dotenv. These files define environment variables that get loaded when the application starts. To verify which variables are loaded, you can print the environment after loading the .env file, or use debugging tools to inspect the variable values at runtime.

Node.js and JavaScript Environments

Node.js applications access environment variables through the process.env object. You can display all variables by running node -e "console.log(process.env)" from the command line, or by including console.log(process.env) in your application code. This outputs a JavaScript object containing all environment variables as key-value pairs.

For more readable output, you can format the environment object: node -e "console.table(process.env)" displays variables in a table format (in Node.js versions that support console.table). Alternatively, node -e "Object.keys(process.env).forEach(key => console.log(key + '=' + process.env[key]))" produces output similar to Unix's printenv command.

"Container and virtual environments create isolated configuration spaces that require context-specific commands to inspect, making it essential to understand the environment layer you're working in."

Security Considerations When Displaying Environment Variables

Environment variables often contain sensitive information like API keys, database passwords, and authentication tokens. Displaying these variables carelessly can expose critical secrets, leading to security breaches. Understanding the security implications of viewing and logging environment variables is essential for maintaining secure systems.

Risks of Exposing Sensitive Variables

When you run commands like printenv or set without arguments, the output includes all environment variables, including those containing secrets. If you copy this output into documentation, share it in a support ticket, or include it in log files, you're potentially exposing sensitive credentials to unauthorized parties. Even screenshots of terminal windows can reveal secrets if environment variables are visible.

Automated logging systems present particular risks. Many applications log their startup environment for debugging purposes, and if these logs are stored insecurely or shared with third parties (like error tracking services), secrets can leak. Similarly, CI/CD systems often expose environment variables in build logs, and without proper masking, these secrets become visible to anyone with access to the build history.

Best Practices for Secure Variable Display

When you need to display environment variables for troubleshooting or documentation, follow these protective practices:

  • ๐Ÿ”’ Use specific variable names instead of listing all variables
  • ๐Ÿ”’ Mask or redact sensitive values before sharing output
  • ๐Ÿ”’ Avoid including environment dumps in version control
  • ๐Ÿ”’ Configure logging systems to filter sensitive variable names
  • ๐Ÿ”’ Use secure channels when sharing environment information

Instead of running printenv and sharing the entire output, query specific non-sensitive variables individually. If you must share a full environment listing, use tools like sed or awk to mask sensitive values: printenv | sed 's/\(PASSWORD=\).*/\1[REDACTED]/' replaces password values with a redacted marker while preserving the variable name.

Many modern tools include built-in secret masking. GitHub Actions automatically masks registered secrets in log output, and similar features exist in GitLab CI, CircleCI, and other platforms. However, these systems only protect known secrets, so you should still follow the principle of least exposure by only displaying variables when necessary.

"The convenience of displaying all environment variables must always be balanced against the security risk of exposing sensitive credentials that could compromise your entire system."

Troubleshooting Common Environment Variable Issues

When environment variables don't work as expected, the problem often lies in scope, inheritance, or shell configuration. Understanding how to diagnose these issues through strategic variable display can save hours of frustration.

Variables Not Appearing or Having Unexpected Values

If a variable you expect to see doesn't appear when you run printenv or echo, first verify that it's actually set in your current context. Variables set in one terminal window don't automatically appear in others unless they're defined in shell startup files. Run printenv VARIABLE_NAME to check if the variable exists at all. If it returns nothing, the variable isn't set in your current environment.

Check your shell's startup files (.bashrc, .bash_profile, .zshrc, etc.) to see where variables are defined. Variables set in .bashrc typically only apply to interactive shells, while those in .bash_profile apply to login shells. This distinction causes confusion when variables work in terminal windows but not in scripts or cron jobs. To debug this, add printenv > /tmp/env-debug.txt to your script and examine the resulting file to see exactly what environment the script receives.

Path and Execution Issues

The PATH variable deserves special attention because it determines which programs your system can find and execute. If commands that should work return "command not found" errors, display your PATH variable: echo $PATH on Unix systems or echo %PATH% on Windows. The output shows a list of directories separated by colons (Unix) or semicolons (Windows).

If a directory is missing from PATH, your system won't find executables in that location. You can temporarily add a directory with export PATH=$PATH:/new/directory on Unix or set PATH=%PATH%;C:\new\directory on Windows. To make the change permanent, add the export command to your shell's startup file or use the system's environment variable configuration interface.

Sometimes PATH becomes corrupted with duplicate entries or invalid directories. Display the PATH with each directory on a separate line for easier inspection: echo $PATH | tr ':' '\n' on Unix systems. This formatted output makes it easy to spot duplicates, typos, or non-existent directories that might be causing problems.

Variable Inheritance and Process Boundaries

Child processes inherit environment variables from their parents, but changes in child processes don't propagate back to parents. This one-way inheritance causes confusion when you set a variable in a script and expect it to persist after the script exits. To demonstrate this behavior, create a simple script that sets a variable and then check if that variable exists after running the scriptโ€”it won't, because the variable was set in the script's child process and disappeared when the script terminated.

To verify what environment a child process receives, use the env command to run a program with a modified environment while displaying what was passed: env | grep MYVAR; env MYVAR=test env | grep MYVAR shows the difference between the current environment and the modified environment passed to the child process.

"Understanding environment variable scope and inheritance patterns is crucial for diagnosing why variables appear in some contexts but mysteriously vanish in others."

Advanced Techniques for Environment Variable Management

Beyond basic display commands, advanced users can leverage sophisticated techniques for managing, monitoring, and documenting environment variables across complex systems. These approaches become essential when working with large teams, multiple environments, or intricate deployment pipelines.

Comparing Environments Across Systems

When troubleshooting issues that occur in production but not in development, comparing environment variables between systems often reveals the root cause. You can export environments from multiple systems and use diff tools to identify discrepancies. On Unix systems, run printenv | sort > env-production.txt on the production server and printenv | sort > env-development.txt on your development machine, then use diff env-production.txt env-development.txt to see the differences.

For more sophisticated comparisons, especially when dealing with many environments, consider using specialized tools or scripts. A simple Python script can load environment exports from multiple sources and highlight differences, showing not just which variables differ but also providing side-by-side value comparisons. This approach scales well when managing dozens of microservices or multiple deployment stages.

Documenting and Versioning Environment Configurations

Maintaining documentation of required environment variables helps onboard new team members and ensures consistent configuration across deployments. Create a template .env file with all required variables but placeholder values, and include comments explaining each variable's purpose. This template serves as both documentation and a starting point for new environments.

Some teams use tools like direnv or dotenv-linter to validate that required environment variables are set before running applications. These tools can check not just that variables exist but also that their values match expected patterns (like URLs, email addresses, or specific formats). Integrating these checks into your development workflow catches configuration issues early, before they cause runtime failures.

Monitoring Environment Changes

In production systems, unexpected changes to environment variables can cause subtle bugs or security issues. Implementing monitoring that tracks environment variable changes helps detect configuration drift or unauthorized modifications. This monitoring can be as simple as periodically capturing the environment and comparing it to a known-good baseline, or as sophisticated as using system auditing tools that log all environment modifications.

For containerized applications, tracking environment variables across deployments helps understand how configuration changes affect application behavior. Many container orchestration platforms provide APIs for querying running container environments, enabling automated checks that verify configurations match expectations. Integrating these checks into deployment pipelines prevents misconfigured containers from reaching production.

Platform-Specific Tips and Considerations

Different operating systems and platforms have unique characteristics that affect how you display and manage environment variables. Understanding these platform-specific details ensures you use the most appropriate methods for your context.

macOS Specific Considerations

macOS combines Unix-like shell environments with GUI applications that have different environment variable contexts. Applications launched from the Finder don't inherit the environment variables set in your shell startup files, which can cause confusion when command-line tools work but GUI applications don't. To view the environment that GUI applications receive, you can use launchctl getenv VARIABLE_NAME or check the system-wide environment by examining /etc/launchd.conf (though this file is deprecated in recent macOS versions).

For macOS-specific environment management, the launchctl command provides control over the launch services environment. Setting variables with launchctl setenv VARIABLE_NAME value makes them available to GUI applications, though these settings don't persist across reboots unless configured in launch agents or daemons.

Windows Subsystem for Linux (WSL) Nuances

WSL creates an interesting hybrid environment where Linux and Windows variables coexist. Within WSL, you can access Windows environment variables that have been automatically imported, typically prefixed with WSLENV. To see which Windows variables are available in WSL, run printenv | grep -i wsl or check the WSLENV variable itself, which lists the Windows variables that should be shared with WSL.

The interaction between Windows and WSL environments can cause confusion when paths or configurations differ between the two systems. If you're troubleshooting cross-platform issues, display variables from both contexts: use PowerShell or Command Prompt to check Windows variables, and use standard Linux commands within WSL to check the Linux environment. Pay particular attention to path variables, as Windows paths use backslashes and drive letters while Linux uses forward slashes and a unified filesystem root.

Cloud Platform and Serverless Environments

Cloud platforms like AWS Lambda, Google Cloud Functions, and Azure Functions inject their own environment variables that provide information about the execution context. These variables include details about the function name, version, memory allocation, and other runtime characteristics. To discover what variables are available in serverless environments, create a simple function that logs the entire environment and examine the output.

Cloud platforms typically provide both web consoles and CLI tools for viewing and managing environment variables. AWS Lambda, for example, lets you view variables through the AWS Console, the AWS CLI (aws lambda get-function-configuration --function-name myfunction), or within the function code itself. Understanding which method to use depends on whether you're debugging, documenting, or automating configuration management.

What's the difference between environment variables and shell variables?

Environment variables are exported to child processes and available to all programs launched from the shell, while shell variables exist only in the current shell session and aren't inherited by child processes. You create a shell variable with VARIABLE=value and convert it to an environment variable by exporting it with export VARIABLE. To see only environment variables, use printenv; to see all shell variables including non-exported ones, use set in Bash.

Why can't I see a variable I just set in another terminal window?

Environment variables set in one terminal session don't automatically appear in other sessions because each terminal runs as a separate process with its own environment. To make variables available across all sessions, add them to your shell's startup file (.bashrc, .zshrc, or .bash_profile) or set them as system-wide variables through your operating system's configuration interface. After modifying startup files, either restart the terminal or source the file with source ~/.bashrc.

How do I display environment variables without revealing sensitive information?

To safely display environment variables, query specific non-sensitive variables individually rather than listing all variables. If you must share a full listing, use filtering commands to mask sensitive values: printenv | sed 's/\(API_KEY=\).*/\1[REDACTED]/' on Unix systems. For documentation purposes, create a template showing variable names with example values rather than real credentials. Many CI/CD platforms automatically mask registered secrets in logs, but you should still minimize exposure by only displaying variables when necessary.

Why does my application see different environment variables than my shell?

Applications can see different variables depending on how they're launched and what environment they inherit. GUI applications often don't inherit shell environment variables because they're launched by the desktop environment rather than your shell. Services and daemons run with minimal environments for security reasons. To verify what environment an application receives, have it log its environment at startup using printenv > /tmp/app-env.txt or equivalent code in the application's language. Then compare this output to your shell environment to identify discrepancies.

How can I make environment variables persist across reboots?

The method for persisting environment variables depends on your operating system and desired scope. On Unix systems, add export statements to shell startup files like .bashrc or .bash_profile for user-specific variables, or to /etc/environment or /etc/profile for system-wide variables. On Windows, use the System Properties dialog or the setx command for persistent user or system variables. For containerized applications, define variables in Dockerfiles, docker-compose.yml files, or orchestration platform configurations. Always test that variables persist by logging out and back in or restarting the system.

What does it mean when a variable shows up in 'set' but not in 'printenv'?

When a variable appears in set output but not in printenv, it's a shell variable that hasn't been exported to the environment. Shell variables are local to the current shell and won't be passed to child processes or programs you run. To make the variable available to other programs, export it with export VARIABLE_NAME. After exporting, the variable will appear in both set and printenv output and will be inherited by child processes launched from that shell.

SPONSORED

Sponsor message โ€” This article is made possible by Dargslan.com, a publisher of practical, no-fluff IT & developer workbooks.

Why Dargslan.com?

If you prefer doing over endless theory, Dargslanโ€™s titles are built for you. Every workbook focuses on skills you can apply the same dayโ€”server hardening, Linux one-liners, PowerShell for admins, Python automation, cloud basics, and more.