Understanding how to set environment variables in Linux is one of those skills that separates casual users from people who actually know what they’re doing. I learned this the hard way during my first Arch install when I managed to completely obliterate my PATH variable and suddenly couldn’t run basic commands like ls or cd. Fun times.
Whether you’re configuring development environments, automating scripts, or just trying to customize your terminal, environment variables are the invisible force controlling how your Linux system behaves. In this guide, I’ll walk you through everything from viewing existing variables to setting permanent ones that survive a reboot.
What Are Environment Variables in Linux (And Why They Matter)
Before we start changing things, let’s make sure you actually understand what we’re working with. Environment variables aren’t as intimidating as they sound once you know what’s happening under the hood.
The Simple Definition: Dynamic Values That Configure Your System
Environment variables are key-value pairs stored in your system’s memory. They act like settings that tell programs where to find things, how to behave, and what your preferences are.
Think of them as labels on boxes in a warehouse. When a program needs to find something, it checks the label instead of searching every box. The PATH variable, for example, tells your shell where to look for executable programs when you type a command.
Get a VPS from as low as $11/year! WOW!
How Environment Variables Work Behind the Scenes
When you log into your Linux system, it reads several configuration files and sets up your environment. These variables exist in memory and get inherited by every program you launch from that session. When you open a terminal and run a script, that script can access all the environment variables from its parent shell.
This inheritance is crucial. It’s why you can set JAVA_HOME once and every Java application automatically knows where to find the JDK.
My First Environment Variable Disaster (And What It Taught Me)
I still remember sitting in front of my monitor at 2 AM during my first Arch install. I wanted to add a custom scripts directory to my PATH. Simple enough, right? Instead of appending to PATH, I overwrote it completely:
export PATH="/home/alexa/scripts"
Suddenly, ls didn’t work. Neither did vim, nano, or basically any command. I had to type the full path to everything: /usr/bin/ls, /usr/bin/nano. It took me an hour to figure out how to fix it, and I learned to always test changes in a temporary session first.
How to View Your Current Environment Variables
Before setting anything new, let’s see what you’re working with. Linux gives you several ways to inspect your current environment.
Using printenv to List All Variables
The printenv command displays all environment variables currently set in your session:
printenv
This outputs everything: your user, home directory, shell, terminal type, and dozens of other variables. It’s a good way to get a snapshot of your environment. You can also use env for similar output.
Using echo to Check Specific Variables
To check a single variable, use echo with the variable name prefixed by a dollar sign:
echo $HOME
echo $PATH
echo $USER
The $ tells your shell to expand the variable and show its value. Without it, you’d just see the literal text “HOME”.
Understanding Common Environment Variables (PATH, HOME, USER, SHELL)
Some variables show up on every Linux system. Here are the ones you’ll encounter most often:
- PATH: Colon-separated list of directories where your shell searches for executables. When you type
git, the shell checks each PATH directory until it finds the binary. Use the which command to see exactly where an executable lives in your PATH. - HOME: Your user’s home directory (usually
/home/username) - USER: Your current username
- SHELL: Path to your default shell (
/bin/bash,/bin/zsh, etc.) - EDITOR: Your preferred text editor for command-line programs
- LANG: System language and locale settings
How to Set Environment Variables Temporarily (Current Session Only)
Sometimes you need a variable for just one task. Maybe you’re testing a configuration or running a script that needs a specific setting. Temporary variables are perfect for this.
Using the export Command: The Basics
The export command sets an environment variable that lasts until you close your terminal:
export MY_VARIABLE="hello world"
echo $MY_VARIABLE
That’s it. The variable exists in your session and any programs you launch from that terminal can access it.
Shell Variables vs Environment Variables (Critical Difference)
Here’s something that trips up beginners. There’s a difference between shell variables and environment variables:
Shell variable (NOT exported):
MY_VAR="test"
Only visible in your current shell. Child processes can’t see it.
Environment variable (exported):
export MY_VAR="test"
Inherited by all child processes launched from this shell.
This matters when you’re running scripts. If you set a shell variable and then run a bash script, that script won’t have access to your variable. But if you export it, the script inherits it from the parent shell. For more on the distinction, check out DigitalOcean tutorial on shell variables.
When to Use Temporary Variables
Temporary variables are useful when:
- Testing configurations before making them permanent
- Running one-off scripts with specific settings
- Overriding default behavior for a single session
- Setting sensitive values you don’t want saved to disk
How to Set Permanent Environment Variables for Your User
Temporary is fine for testing. But eventually, you want variables that survive a reboot. This is where configuration files come in.
Understanding .bashrc vs .bash_profile vs .profile
This confuses everyone at first. Linux has multiple configuration files, and they load at different times:
- .bashrc: Runs for interactive non-login shells (when you open a new terminal window)
- .bash_profile: Runs for login shells (when you log in via console or SSH)
- .profile: Generic profile, read by multiple shells if .bash_profile doesn’t exist
In practice, most people put their environment variables in .bashrc because that’s what runs when you open a terminal. The ArchWiki environment variables documentation has an excellent deep dive if you want to understand all the edge cases.
Adding Variables to .bashrc (The Standard Approach)
Open your .bashrc file with your favorite editor:
nano ~/.bashrc
Add your export statements at the end:
# Custom environment variables
export EDITOR="vim"
export MY_PROJECT_DIR="/home/alexa/projects"
Save the file. The variables won’t take effect until you reload the configuration.
How to Add Directories to Your PATH Variable Permanently
This is the one I messed up early on. The correct way to add a directory to PATH is to append, not overwrite:
export PATH="$PATH:/home/alexa/scripts"
The $PATH expands to your current PATH value, and we’re adding our new directory to the end. You can also prepend if you want your directory checked first:
export PATH="/home/alexa/scripts:$PATH"
Add this line to your .bashrc to make it permanent. I keep all my custom scripts in ~/bin and add it to PATH this way. It’s incredibly useful for cron jobs and automation scripts too, though cron has its own quirks with environment variables.
Reloading Your Configuration Without Logging Out
After editing .bashrc, you don’t need to log out. Just run:
source ~/.bashrc
Or the shorthand:
. ~/.bashrc
Your new variables are now active in the current terminal.
How to Set System-Wide Environment Variables (All Users)
Sometimes you need variables that apply to every user on the system. This requires root access and different configuration files.
Using /etc/environment for Global Variables
The /etc/environment file is shell-agnostic. It accepts simple variable assignments without the export keyword:
JAVA_HOME="/usr/lib/jvm/java-17-openjdk"
MY_GLOBAL_VAR="value"
Edit it with sudo:
sudo nano /etc/environment
Changes apply after users log in again. This file doesn’t support shell scripting, just plain variable=value pairs.
Using /etc/profile.d/ for Shell-Specific Configuration
For more complex setups, create a script in /etc/profile.d/:
sudo nano /etc/profile.d/my-custom-vars.sh
Add your exports:
#!/bin/bash
export COMPANY_NAME="Acme Corp"
export API_ENDPOINT="https://api.example.com"
Make it executable:
sudo chmod +x /etc/profile.d/my-custom-vars.sh
This approach is great for user management in enterprise environments where every user needs access to the same configuration.
When to Use System-Wide vs User-Specific Variables
Use system-wide variables when:
- Multiple users need the same configuration
- Server applications require specific settings
- You’re managing a fleet of similar machines
Use user-specific variables for personal preferences that shouldn’t affect other users on the system.
Security Best Practices for Environment Variables (Critical Reading)
Here’s where I need to be blunt: storing secrets in environment variables is riskier than most tutorials admit. I’ve seen production API keys leaked because someone didn’t understand the exposure.
Why Storing Secrets in Environment Variables Is Risky
Environment variables seem hidden, but they’re actually quite visible:
- Any process can read its own environment variables
ps auxcan expose variables on some systems- Crash reports and error logs often dump environment state
- Container orchestration tools may expose variables in ways you don’t expect
According to Trend Micro security research on environment variables:
“Environment variables containing secrets are frequently exposed through logging mechanisms, often unintentionally. This data exposure can occur in unexpected error logs on the server, a rich debug output, or exception thrown crash reports.”
This isn’t theoretical. The httpoxy vulnerability exploited improperly trusted environment variables to hijack requests. If you’re viewing system logs with journalctl, you might be surprised what shows up.
The .env File Disaster (And How to Avoid It)
I once did a security audit where a company had committed their .env file to a public GitHub repository. It contained database passwords, API keys, and AWS credentials. Within hours of discovery, their AWS account was compromised.
Always add .env to your .gitignore. Better yet, use a .env.example file with placeholder values that you do commit.
Better Alternatives for Sensitive Data
For production secrets, consider:
- HashiCorp Vault: Dedicated secrets management with access control and audit logging
- AWS Secrets Manager / Azure Key Vault: Cloud-native secrets storage
- Docker Secrets: For containerized applications
- SSH keys: For authentication instead of passwords. Learn SSH key generation if you haven’t already.
The Linux Documentation Project secure programming guide covers this in depth if you’re writing applications that handle sensitive data.
The Seven Deadly Sins of Environment Variable Security
- Committing
.envfiles to version control - Storing production credentials in plain text files
- Never rotating secrets
- Logging environment variables in debug output
- Trusting user-controlled variables in privileged programs
- Setting overly permissive file permissions on config files
- Sharing environment files between development and production
Common Environment Variable Use Cases Every Admin Should Know
Let’s look at practical scenarios where environment variables solve real problems.
Configuring Development Environments
When working on multiple projects, environment variables help you switch contexts without modifying code:
export NODE_ENV="development"
export DATABASE_URL="postgres://localhost/myapp_dev"
export DEBUG="true"
Your application reads these values and behaves accordingly. No hardcoded paths or configurations.
Setting Proxy Variables (http_proxy, https_proxy, no_proxy)
On corporate networks behind a proxy, you’ll need these:
export http_proxy="http://proxy.company.com:8080"
export https_proxy="http://proxy.company.com:8080"
export no_proxy="localhost,127.0.0.1,.company.com"
Many command-line tools respect these variables automatically. The curl command, for example, will route requests through your configured proxy.
Customizing Your Terminal (PS1, EDITOR, LANG)
Environment variables control your shell experience too:
# Set default editor for git commits, crontab, etc.
export EDITOR="vim"
# Customize your prompt (this is just a basic example)
export PS1="\u@\h:\w$ "
# Set language and encoding
export LANG="en_US.UTF-8"
These go in your .bashrc alongside any alias command definitions you’ve set up.
Application-Specific Variables
Many applications use specific environment variables:
JAVA_HOMEfor Java applicationsGOPATHfor Go developmentPYTHONPATHfor Python module search pathsAWS_PROFILEfor AWS CLI configuration
Troubleshooting Environment Variables (When Things Go Wrong)
Even experienced admins run into issues. Here’s how to debug common problems.
My Variable Isn’t Being Recognized
Check these issues in order:
- No spaces around the equals sign:
VAR="value"works.VAR = "value"does not. - Did you export it? Without
export, child processes can’t see the variable. - Did you source the file? After editing
.bashrc, runsource ~/.bashrc. - Typos: Variable names are case-sensitive.
$PATHand$pathare different.
PATH Variable Broke and Commands Don’t Work
If you’ve corrupted your PATH (like I did), you can still run commands with full paths:
/usr/bin/nano ~/.bashrc
Fix your PATH definition, save, and either run /bin/bash to start a fresh shell or log out and back in. You can also use the grep command to search your config files: /usr/bin/grep PATH ~/.bashrc
Changes Aren’t Persisting After Reboot
If your variables disappear after reboot:
- Make sure you’re editing the right file (
.bashrcfor most cases) - Check that the file actually contains your export statements
- Verify you’re using a login shell vs non-login shell
- Look for other configuration files that might override yours
Advanced Tips: Managing Environment Variables Like a Pro
Once you’ve mastered the basics, these tips will keep your environment clean and maintainable.
Using unset to Remove Variables
To remove a variable from your environment:
unset MY_VARIABLE
This removes it from the current session. To remove it permanently, delete the export line from your configuration file.
Validating and Sanitizing Variable Values
In scripts, always validate environment variables before using them:
if [ -z "$DATABASE_URL" ]; then
echo "Error: DATABASE_URL is not set"
exit 1
fi
Never trust user-controlled environment variables in privileged scripts. Sanitize inputs and use explicit paths.
Documentation and Naming Conventions
Keep your .bashrc organized with comments:
# Development environment
export NODE_ENV="development"
# Custom scripts directory (added 2025-01)
export PATH="$PATH:$HOME/bin"
# Java configuration
export JAVA_HOME="/usr/lib/jvm/java-17-openjdk"
Use UPPERCASE_WITH_UNDERSCORES for variable names. This is the convention, and it helps distinguish environment variables from local shell variables.
Wrapping Up: Environment Variables Are Foundational
Learning how to set environment variables in Linux unlocks a whole layer of system control. From customizing your shell to configuring complex applications, these key-value pairs are everywhere.
Start simple. Set a few temporary variables, experiment with your .bashrc, and pay attention to what breaks when you change things. That’s how I learned, and it’s the best way to internalize how the system actually works.
If you’re building out your Linux administration skills, I’d recommend checking out our guides on scheduling cron jobs (which depend heavily on environment variables) and creating shell aliases to make your terminal even more powerful.




