Managing Linux Environment Variables
Environment variables play a crucial role in Linux systems by storing information that can be accessed by various processes and applications.
Properly managing these variables helps customize your working environment and ensure applications function correctly.
This guide covers everything you need to know about viewing, setting, and removing environment variables in Linux.
What Are Environment Variables?
Environment variables are dynamic values that affect how processes run on your system. They’re part of the environment in which a process runs and typically consist of a name-value pair like NAME=value
.
Viewing Environment Variables
View All Environment Variables
To display all currently set environment variables, use either:
1 |
|
or
1 |
|
View a Specific Environment Variable
To check the value of a particular variable:
1 |
|
For example:
1 |
|
Setting Environment Variables
Temporary: For Current Session Only
To set a variable for the current shell session only:
1 |
|
To make this variable available to child processes (export it):
1 |
|
For example:
1 |
|
Permanent: User-Specific Settings
To make variables persist across sessions for a specific user, add them to shell configuration files:
- For Bash users, edit
~/.bashrc
or~/.bash_profile
:
1 |
|
- For Zsh users, edit
~/.zshrc
:
1 |
|
- Load the changes without restarting your session:
1 |
|
Permanent: System-Wide Settings
To set variables for all users:
- Create a file in
/etc/profile.d/
:
1 |
|
- Add your exports:
1 |
|
- Make it executable:
1 |
|
Another system-wide option is to add entries to /etc/environment
:
1 |
|
Add variables in the format:
1 |
|
Note: /etc/environment
doesn’t support shell functions or commands - only simple variable assignments.
Removing Environment Variables
For Current Session
To unset a variable in the current session:
1 |
|
Permanently
To permanently remove a variable, edit the file where it was defined and remove or comment out the corresponding line, then reload the configuration file.
Appending to Existing Variables
To add values to existing variables like PATH:
1 |
|
This preserves the original value while adding new content.
Common Environment Variables
PATH
: Directories searched for executable filesHOME
: Current user’s home directoryUSER
: Current usernameSHELL
: Path to current shellLANG
: System language and localePWD
: Current working directoryTERM
: Terminal type
Best Practices
- Use descriptive variable names (preferably uppercase)
- Avoid spaces in values without quotes
- Organize environment variables by purpose
- Document non-standard variables
- Be careful with system variables like PATH - always append rather than overwrite