How to List, Set and Manage Linux Environment Variables
Environment variables tell your shell and programs how to behave, from where to find executables to which editor to open. They are a core part of Linux system administration, and knowing how to work with them gives you fine control over your environment.
You will learn how to list, set, delete, and make environment variables permanent, how they differ from shell variables, and how to handle those that contain sensitive data. The examples run on a single server, so you finish with techniques you can apply to scripts and services right away.
#What are environment variables in Linux
Linux environment variables are dynamic variables used by a shell and its child processes. The shell serves as the primary command-line interface for system administrators and developers to perform advanced tasks on Linux systems. Environment variables define a variety of aspects related to how a Linux system works.
For example, a user's default shell is defined in the SHELL variable. Similarly, many administrators use the JAVA_HOME= environment variable to point programs to specific versions of Java on a system.
A few key points to keep in mind when working with Linux environment variables are:
-
Environment variables follow
<NAME>=<VALUE>formatting. -
You can specify multiple values for a single variable by separating them with colons like this:
<NAME>=<VALUE1>:<VALUE2>:<VALUE3> -
Environment variables are case-sensitive.
-
By convention, but not rule, environment variable names are always capitalized.
-
Shell variables are not the same as environment variables. Shell variables only apply to the current shell, not any child processes. We'll take a closer look at this topic in the Linux shell variables vs. Linux environment variables section.
With all that in mind, let's move on to the Linux environment variables setup tutorial.
#Prerequisites
Our examples use Ubuntu 24.04 and GNU Bash 5.2.21, though you can follow along on most modern Linux distributions. Several methods exist for listing Linux environment variables, and this guide covers the most common ones.
#1. How to list Linux environment variables
Now that we know what environment variables in Linux are, what they are used for, and have defined the prerequisites needed to set and list Linux environment variables, let's look at ways to get you started.
#Use printenv to list Linux environment variables
The printenv command displays the current environment variables.
You can use printenv to list all your current Linux environment variables by running the command without any options or parameters.
printenv
The output should look similar to this:
OutputSHELL=/bin/bash
SUPERBREAKFAST=Pepper and Egg
PWD=/root
LOGNAME=root
XDG_SESSION_TYPE=tty
MOTD_SHOWN=pam
HOME=/root
LANG=C.UTF-8
SSH_CONNECTION=24.148.23.154 2068 84.32.188.154 22
EASTEREGG=You pay attention to detail, good job!
USER=root
SHLVL=1
XDG_RUNTIME_DIR=/run/user/0
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
SSH_TTY=/dev/pts/0
_=/usr/bin/printenv
You can also use printenv to display individual environment variables. The basic syntax to display a single Linux environment variable with printenv is: printenv [name]
For example, to print the PWD environment variable, use this command:
printenv PWD
The output should display your shell's current working directory.
Output/root
#Use env to list Linux environment variables
The env command can list all environment variables with output similar to printenv. To use env to list all your Linux environment variables, run the command with no options or parameters, like this:
env
In most cases, the env output should match the output of printenv except for the _= variable. This happens because the _= variable is a special Bash parameter used to invoke a shell or shell script. If you use env on a modern Linux system, the _= value will match the location of the env binary (e.g. /usr/bin/env). If you use printenv, it will match the location of the printenv binary (e.g. /usr/bin/printenv).
#Use echo to display a Linux environment variable
One of the quickest ways to display a single Linux environment variable is to use the echo command. The basic syntax is echo $<variable_name>.
For example, to print the PATH environment variable, use this command:
echo $PATH
The output should look similar to:
Output/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
The echo $<variable_name> command also works for shell variables that are NOT environment variables. For example, if we create a BREAKFAST variable and set it to 'Pepper & Egg', we can see the output with echo $BREAKFAST but not with printenv.
BREAKFAST='Pepper & Egg'
echo $BREAKFAST
OutputPepper & Egg
The printenv BREAKFAST line prints nothing because BREAKFAST is a shell variable rather than an environment variable.
printenv BREAKFAST
#Other methods to list Linux environment variables
Other methods for listing Linux environment variables include:
declare- this built-in shell utility can display shell and environment variables using this command.
BASH=/usr/bin/bash
BASH_VERSINFO=([0]="5" [1]="2" [2]="21" [3]="1" [4]="release" [5]="x86_64-pc-linux-gnu")
HOME=/root
LANG=C.UTF-8
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
PWD=/root
SHELL=/bin/bash
TERM=xterm
USER=root
set- displays shell variables, environment variables, and shell functions.
BASH=/usr/bin/bash
BASHOPTS=checkwinsize:cmdhist:complete_fullquote:expand_aliases:extquote
HOME=/root
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
PWD=/root
SHELL=/bin/bash
USER=root
command_not_found_handle ()
{
...
}
compgen -v- displays the names of all your shell and environment variables (without their values).
BASH
BASHOPTS
BASH_VERSINFO
HOME
LANG
PATH
PWD
SHELL
TERM
USER
#Common Linux environment variables
Linux sets a number of standard environment variables that shape how your shell and programs behave. The table below lists the ones you will run into most often and what each controls.
| Variable | What it holds |
|---|---|
PATH |
Directories the shell searches for executable commands |
HOME |
The current user's home directory |
USER |
The username of the logged-in user |
SHELL |
Path to the user's default shell |
PWD |
The current working directory |
LANG |
The system locale and character encoding |
TERM |
The terminal type, which controls colors and formatting |
EDITOR |
The default text editor for command-line programs |
#2. How to set Linux environment variables
The basic command to set a Linux environment variable is
export <NAME>='<value>'
For example, to create an environment variable named SANDWICH with a value of Pepper And Egg, use this command:
export SANDWICH='Pepper And Egg'
To confirm that the environment variable was created, use the command
printenv SANDWICH
The output should be as follows:
OutputPepper And Egg
#Set an environment variable for a single command
Sometimes you want a variable to apply to a single command without affecting the rest of your session. Place the assignment directly before the command, on the same line.
GREETING='Hello' bash -c 'echo $GREETING'
The command prints Hello, but the variable does not persist. Run printenv GREETING afterward, and you get no output, because the assignment applied only to that single command. The pattern is handy for passing a one-off setting to a program, such as DEBUG=1 ./myscript.sh.
#How to create a shell variable
You can create shell variables using this basic command structure <NAME>='<value>'.
For example, to create a shell variable named COOLSERVER with a value of Cherry, use this command:
COOLSERVER='Cherry'
You can confirm the variable now exists using this command:
echo $COOLSERVER
The output should be:
OutputCherry
To confirm the variable is not an environment variable, execute this command:
printenv COOLSERVER
Because the variable isn't an environment variable, there should be no output:
#How to convert a shell variable to an environment variable
To convert a shell variable to an environment variable, the basic command syntax is export <Shell_Variable_Name>.
For example, to convert the COOLSERVER variable from the previous example to an environment variable, use this command:
export COOLSERVER
Now, the printenv COOLSERVER command should print Cherry as the output:
OutputCherry
#Linux shell variables vs. Linux environment variables
With what we have covered so far, you can see that shell variables and environment variables are different things. Now, let's take a closer look at the difference and why it matters.
The key difference between Linux shell variables and Linux environment variables is: shell variables are not shared with a shell's child processes, environment variables are shared with a shell's child processes.
To demonstrate why that difference is important, let's walk through an example with a simple bash script.
First, create a variable named CLOUD and set the value to Cherry Servers!
CLOUD='Cherry Servers!'
Next, use the echo command to display the variable.
echo $CLOUD
Here's what that looks like end-to-end:
OutputCherry Servers!
Now, create a test.sh bash script that includes the same command. The script should look like this:
#!/bin/bash
echo $CLOUD
Make the script executable with this command:
chmod +x test.sh
Now, run the script:
./test.sh
The output should be blank.
The reason the output is blank is that $CLOUD is a shell variable. It is contained within the current shell instance. Meanwhile, the test.sh script initiates a new process, and, since the $CLOUD environment variable is not set, the script doesn't print anything.
Let's make $CLOUD an environment variable with this command (note do NOT use the $ before the variable name):
export CLOUD
Now, run the test.sh script again.
./test.sh
You should see this output:
OutputCherry Servers!
#3. How to delete Linux environment variables
The basic syntax to delete an existing Linux environment variable is unset <NAME>.
For example, to unset our COOLSERVER variable, use this command:
unset COOLSERVER
To confirm the variable is now deleted, execute this command:
printenv COOLSERVER
Because the variable isn't an environment variable, there should be no output:
#4. How to make Linux environment variables permanent
The environment variables we've created so far will only last for the duration of your shell session. If you log out or reboot, you would need to recreate them if you want to use them.
Fortunately, there are several ways to make Linux environment variables persist across different shell sessions.
#Use .profile to make environment variables permanent for login shells
The .profile file exists in a user's home directory. You can add environment variables for a user by editing their .profile file to include export commands that set them.
For example, to make our COOLSERVER environment variable permanent for our current user, follow this process:
-
Change the directory to the user's home directory
cd ~ -
Open
.profilefile in a text editor (e.g. nano, vi, vim, etc.) -
Add the following line to the bottom of the file:
export COOLSERVER='Cherry' -
Save the changes
The changes will take effect on the next login. You can make them take effect for the current terminal using this command:
. ~/.profile
#Use .bashrc to make environment variables permanent for non-login interactive shells
For non-login shells, you can follow the same process as login shells, but instead of editing ~/.profile file, edit ~/.bashrc.
#Which startup file loads for which shell
The file you edit depends on the type of shell that starts. The table below maps the common startup files to the times when each runs.
| File | Loads for |
|---|---|
/etc/environment |
All sessions, system-wide, read by PAM (Pluggable Authentication Modules) at login |
/etc/profile and /etc/profile.d/*.sh |
Login shells, system-wide |
~/.profile or ~/.bash_profile |
Login shells, single user |
~/.bashrc |
Non-login interactive shells, single user |
A login shell runs when you sign in over SSH or on the console. An interactive non-login shell runs when you open a new terminal within an existing session. Many distributions source ~/.bashrc from ~/.profile, so a value set in ~/.bashrc often applies to both.
#Use /etc/environment to make environment variables permanent system-wide
⚠️ Warning: Any shell on the system can access system-wide variables, so set them with caution.
To set system-wide Linux environment variables, you can edit the /etc/environment file. Instead of appending export commands to the file, append the <NAME>='<VALUE>' pair to the end of the file.
For example, to make our COOLSERVER environment variable permanent for the entire system, follow this process:
-
Change directory to the user's home directory
cd /etc -
Open
environmentfile in a text editor (e.g. nano, vi, vim, etc.) -
Add the following line to the bottom of the file
COOLSERVER='Cherry' -
Save the changes
#Use /etc/profile.d for system-wide variables
Editing /etc/environment works for simple values, but that file is read by PAM, not run as a script. It accepts only plain NAME=VALUE pairs, with no export keyword and no variable expansion. When you need logic, expansion, or anything beyond a static value, add a script under /etc/profile.d instead.
Create a file ending in .sh and add your export commands.
echo 'export COOLSERVER="Cherry"' | sudo tee /etc/profile.d/coolserver.sh
Login shells read every .sh file in /etc/profile.d at startup, so the variable applies to all users on the next login. The approach keeps custom variables separate from system files, making them easy to review or remove.
#Set environment variables for systemd services
Shell startup files do not apply to services managed by systemd, since those processes do not start from an interactive shell. To pass variables to a service, set them in the unit file with the Environment= directive.
[Service]
Environment="API_HOST=localhost"
Environment="API_PORT=8080"
For several values, or for secrets you would rather keep out of the unit file, use EnvironmentFile= to load them from a separate file.
[Service]
EnvironmentFile=/etc/myapp/env
After editing a unit file, reload systemd and restart the service for the changes to take effect.
sudo systemctl daemon-reload
sudo systemctl restart myapp
Also read: How to install deb file on Ubuntu 22.04
#How to handle and protect Linux environment variables securely
Creating and listing environment variables in Linux is easy but the crucial aspect in the environment variable lifecycle is managing and auditing them. Environment variables must be audited regularly to ensure that the values they are assigned are correct and secure.
By doing this, you will make sure that processes don't crash just because a function got the wrong value from an outdated environment variable. Below are the ways you can follow to secure environment variables.
-
Limit access scope and avoid storing sensitive data directly: A simple way to avoid authorization of environment variables is to limit their scope through sessions and user profiles. By using sessions and user profiles, you ensure that environment variables are used at the right time and by the right people.
Not every user needs access to sensitive data in environment variables. A login shell (such as bash or zsh) initializes environment variables and session-specific settings based on files like .bash_profile, .bashrc, or .profile.
-
Avoid storing sensitive data directly: In addition to limiting the scope of environment variable access, you have to avoid storing secrets directly in environment variables. Environment variables are consistently tracked by version control systems.
Therefore, secrets embedded in environment variables can end up in cloud repositories. You should use files that are ignored by version control systems, such as .env files, or use secrets management tools such as HashiCorp Vault.
-
Regularly audit environment variables: It is imperative to keep track of all environment variables and remove any redundant or incorrect variables. In addition, schedule periodic rotations for passwords, API keys, and other sensitive environment variables. Doing this will make sure that all processes function properly and your workflow is clean.
-
Validate and sanitize variables: Environment variables should be thoroughly validated and sanitized before being utilized in scripts or applications. Improperly handled variables pose a significant security risk, as attackers can exploit them through injection attacks and privilege escalation. Ensure environment variables match expected formats or data types.
-
Keep secrets out of your shell history: When you type a variable assignment with a secret directly on the command line, the shell records it in
~/.bash_history. Anyone who reads that file later can recover the value.Set sensitive variables from a protected file instead, or prefix the command with a space when your shell is configured to ignore space-prefixed history entries.
-
Remember that
setexposes more than variables: Thesetcommand lists shell functions alongside variables, so its output can reveal logic and values you did not intend to share. Preferprintenvorcompgen -vwhen you only need variable names or values.
#Next steps with Linux environment variables
You can now list environment variables with printenv and env, set them with export, scope them to a single command, remove them with unset, and persist them through shell startup files, /etc/profile.d, or systemd units. You also know how to keep the sensitive ones out of version control and shell history.
For deeper reference, the man pages for bash, export, and env cover the underlying behavior in full. From here, try moving a script's hardcoded settings into environment variables, then load them from a file so the same script runs cleanly across your servers.
FAQs
What is the difference between a shell variable and an environment variable?
A shell variable exists only in the current shell and is not passed to child processes. An environment variable is exported, so any program the shell starts inherits it.
How do I make an environment variable permanent?
Add an `export` line to `~/.profile` or `~/.bashrc` for a single user, to a script under `/etc/profile.d` for all users, or a `NAME=VALUE` pair to `/etc/environment` for a static system-wide value.
How do I view all environment variables in Linux?
Run `printenv` or `env` to list the variables and their values, or `compgen -v` to list only the names.
How do I set the PATH variable permanently?
Add a line such as `export PATH="$PATH:/new/directory"` to `~/.profile` or `~/.bashrc`, then reload it with `source ~/.profile`. Keep `$PATH` in the value so you extend the existing path instead of replacing it.
Why does my variable disappear after I close the terminal?
Variables set in a session last only for that session. To keep one, add it to a shell startup file or another persistent location so it loads on each login.
How do I delete an environment variable?
Run `unset VARIABLE_NAME`. To remove it permanently, also delete its line from whichever startup file or system file defined it.
Get 100% dedicated resources for high-performance workloads.