How to set environment variables in Linux
How to Set Environment Variables in Linux
Environment variables are fundamental components of the Linux operating system that store configuration data, system paths, and application settings. Understanding how to properly set and manage environment variables is crucial for system administration, application development, and customizing your Linux environment. This comprehensive guide will walk you through everything you need to know about setting environment variables in Linux.
What Are Environment Variables?
Environment variables are dynamic named values that affect the way running processes behave on a Linux system. They serve as a communication mechanism between the operating system and applications, storing important configuration information such as system paths, user preferences, and application settings.
These variables exist in the environment space of every process and can be inherited by child processes. Common examples include `PATH` (which defines where the system looks for executable files), `HOME` (your home directory location), and `USER` (your current username).
Types of Environment Variables
System-wide Variables
System-wide environment variables affect all users on the system and are typically used for system configuration. These are usually set in system configuration files and require administrative privileges to modify.
User-specific Variables
User-specific variables only affect a particular user's environment and can be modified by that user without administrative privileges. These are ideal for personal customizations and application-specific settings.
Session Variables
Session variables are temporary and only exist for the duration of the current shell session. Once you close the terminal or log out, these variables are lost.
Viewing Current Environment Variables
Before setting new environment variables, it's helpful to understand how to view existing ones.
Using the `env` Command
```bash
env
```
This command displays all current environment variables and their values.
Using the `printenv` Command
```bash
printenv
```
Similar to `env`, this shows all environment variables. You can also view specific variables:
```bash
printenv PATH
printenv HOME
```
Using the `echo` Command
To display a specific variable's value:
```bash
echo $PATH
echo $HOME
echo $USER
```
Using the `set` Command
```bash
set
```
This displays all variables, including shell variables and functions, not just environment variables.
Methods to Set Environment Variables
Temporary Variables (Session-only)
Using the `export` Command
The most common way to set temporary environment variables is using the `export` command:
```bash
export VARIABLE_NAME="value"
```
Examples:
```bash
export DATABASE_URL="postgresql://localhost:5432/mydb"
export API_KEY="your-secret-api-key"
export CUSTOM_PATH="/opt/myapp/bin"
```
Setting Variables Without Export
You can also set variables without making them available to child processes:
```bash
VARIABLE_NAME="value"
```
To make it available to child processes later:
```bash
export VARIABLE_NAME
```
Combining Variable Setting and Command Execution
Set a variable for a single command execution:
```bash
MY_VAR="temporary_value" command_to_run
```
Example:
```bash
NODE_ENV="production" npm start
```
Permanent Variables
User-specific Permanent Variables
~/.bashrc File
The `.bashrc` file is executed for interactive non-login shells. Add your variables here:
```bash
Open the file in your preferred editor
nano ~/.bashrc
Add your environment variables
export DATABASE_URL="postgresql://localhost:5432/mydb"
export JAVA_HOME="/usr/lib/jvm/java-11-openjdk"
export PATH="$PATH:/opt/myapp/bin"
Save and apply changes
source ~/.bashrc
```
~/.bash_profile File
This file is executed for login shells:
```bash
nano ~/.bash_profile
Add your variables
export EDITOR="vim"
export BROWSER="firefox"
Apply changes
source ~/.bash_profile
```
~/.profile File
The `.profile` file is shell-independent and works with various shells:
```bash
nano ~/.profile
Add shell-independent variables
export LANG="en_US.UTF-8"
export LC_ALL="en_US.UTF-8"
Apply changes
source ~/.profile
```
~/.zshrc File (for Zsh users)
If you're using Zsh shell:
```bash
nano ~/.zshrc
Add your variables
export NVM_DIR="$HOME/.nvm"
export GOPATH="$HOME/go"
Apply changes
source ~/.zshrc
```
System-wide Permanent Variables
/etc/environment File
This file sets environment variables system-wide:
```bash
sudo nano /etc/environment
Add variables (note: no export command needed)
DATABASE_HOST=localhost
API_TIMEOUT=30
CUSTOM_CONFIG_PATH=/etc/myapp
```
/etc/profile File
Sets variables for all users' login shells:
```bash
sudo nano /etc/profile
Add at the end
export JAVA_HOME="/usr/lib/jvm/default-java"
export MAVEN_HOME="/opt/maven"
export PATH="$PATH:$MAVEN_HOME/bin"
```
/etc/profile.d/ Directory
Create custom script files in this directory:
```bash
sudo nano /etc/profile.d/myapp.sh
Add your variables
export MYAPP_HOME="/opt/myapp"
export MYAPP_CONFIG="/etc/myapp/config"
export PATH="$PATH:$MYAPP_HOME/bin"
Make executable
sudo chmod +x /etc/profile.d/myapp.sh
```
Practical Examples and Use Cases
Development Environment Setup
Setting Up Node.js Environment
```bash
Add to ~/.bashrc
export NODE_ENV="development"
export NODE_PATH="/usr/local/lib/node_modules"
export NVM_DIR="$HOME/.nvm"
```
Java Development Setup
```bash
Add to ~/.bashrc or ~/.profile
export JAVA_HOME="/usr/lib/jvm/java-11-openjdk"
export CLASSPATH=".:$JAVA_HOME/lib"
export PATH="$PATH:$JAVA_HOME/bin"
```
Python Development
```bash
Virtual environment and Python path
export PYTHONPATH="/home/user/myproject:$PYTHONPATH"
export VIRTUAL_ENV_DISABLE_PROMPT=1
export PIP_REQUIRE_VIRTUALENV=true
```
Database Configuration
PostgreSQL Settings
```bash
export PGHOST="localhost"
export PGPORT="5432"
export PGUSER="myuser"
export PGDATABASE="mydb"
```
MySQL Configuration
```bash
export MYSQL_HOST="localhost"
export MYSQL_USER="root"
export MYSQL_PASSWORD="secure_password"
```
Application-specific Variables
Docker Environment
```bash
export DOCKER_HOST="unix:///var/run/docker.sock"
export DOCKER_BUILDKIT=1
export COMPOSE_DOCKER_CLI_BUILD=1
```
Git Configuration
```bash
export GIT_EDITOR="vim"
export GIT_PAGER="less"
export GIT_AUTHOR_NAME="Your Name"
export GIT_AUTHOR_EMAIL="your.email@example.com"
```
Modifying the PATH Variable
The `PATH` variable is one of the most commonly modified environment variables. It tells the system where to look for executable files.
Viewing Current PATH
```bash
echo $PATH
```
Adding Directories to PATH
Temporary Addition
```bash
export PATH="$PATH:/new/directory/path"
```
Adding to Beginning of PATH
```bash
export PATH="/new/directory/path:$PATH"
```
Permanent Addition
Add to your shell configuration file:
```bash
In ~/.bashrc
export PATH="$HOME/bin:$PATH"
export PATH="$PATH:/opt/myapp/bin"
```
Example: Adding Custom Script Directory
```bash
Create a bin directory in your home folder
mkdir ~/bin
Add it to PATH in ~/.bashrc
echo 'export PATH="$HOME/bin:$PATH"' >> ~/.bashrc
Reload configuration
source ~/.bashrc
```
Best Practices
Naming Conventions
- Use uppercase letters for environment variable names
- Separate words with underscores
- Use descriptive names: `DATABASE_URL` instead of `DB`
- Avoid spaces in variable names
Security Considerations
- Never store sensitive information like passwords in system-wide files
- Use proper file permissions for configuration files
- Consider using secret management tools for production environments
- Be cautious with variables containing API keys or tokens
Organization Tips
- Group related variables together in configuration files
- Add comments to explain complex or non-obvious variables
- Use consistent formatting and indentation
- Document custom variables for team members
Examples of Good Practices
```bash
Database Configuration
export DB_HOST="localhost"
export DB_PORT="5432"
export DB_NAME="myapp_production"
Application Settings
export APP_ENV="production"
export APP_DEBUG="false"
export APP_LOG_LEVEL="info"
External Service Configuration
export REDIS_URL="redis://localhost:6379/0"
export ELASTICSEARCH_URL="http://localhost:9200"
```
Troubleshooting Common Issues
Variables Not Persisting
Problem: Environment variables disappear after closing terminal.
Solution:
- Ensure you're adding variables to the correct configuration file
- Use `source` command to reload configuration
- Check file permissions and syntax
```bash
Reload configuration
source ~/.bashrc
Check if file is readable
ls -la ~/.bashrc
```
Variables Not Available to Applications
Problem: Applications can't access environment variables.
Solution:
- Use `export` command to make variables available to child processes
- Restart applications after setting variables
- Check if the application is reading from the correct environment
```bash
Wrong way (variable not exported)
MY_VAR="value"
Correct way
export MY_VAR="value"
```
PATH Not Updated
Problem: New directories added to PATH are not recognized.
Solution:
```bash
Check current PATH
echo $PATH
Reload shell configuration
source ~/.bashrc
Or start a new terminal session
exec $SHELL
```
Permission Denied Errors
Problem: Cannot modify system-wide environment files.
Solution:
```bash
Use sudo for system files
sudo nano /etc/environment
Check file permissions
ls -la /etc/environment
Ensure proper ownership
sudo chown root:root /etc/environment
```
Variable Contains Spaces or Special Characters
Problem: Variables with spaces or special characters not working correctly.
Solution:
```bash
Always quote values with spaces
export MY_PATH="/path with spaces/bin"
export COMPLEX_VAR="value with & special characters"
Use single quotes to prevent expansion
export LITERAL_VAR='$HOME will not be expanded'
```
Debugging Variable Issues
```bash
Check if variable is set
if [ -z "$MY_VAR" ]; then
echo "MY_VAR is not set"
else
echo "MY_VAR is set to: $MY_VAR"
fi
List all variables containing specific text
env | grep -i java
Check variable type
declare -p MY_VAR
```
Advanced Techniques
Conditional Variable Setting
```bash
Set variable only if not already set
export JAVA_HOME="${JAVA_HOME:-/usr/lib/jvm/default-java}"
Set based on condition
if [ "$USER" = "developer" ]; then
export DEBUG_MODE="true"
fi
```
Using Variables in Scripts
```bash
#!/bin/bash
Script that uses environment variables
DB_HOST="${DB_HOST:-localhost}"
DB_PORT="${DB_PORT:-5432}"
echo "Connecting to database at $DB_HOST:$DB_PORT"
```
Unsetting Variables
```bash
Remove a variable
unset VARIABLE_NAME
Remove from current session
unset TEMP_VAR
Example
export TEST_VAR="temporary"
echo $TEST_VAR # Shows: temporary
unset TEST_VAR
echo $TEST_VAR # Shows: (empty)
```
Conclusion
Setting environment variables in Linux is a fundamental skill that enhances system configuration, application deployment, and development workflow. Whether you need temporary variables for testing, user-specific customizations, or system-wide configurations, understanding the various methods and best practices ensures your Linux environment works efficiently and securely.
Remember to choose the appropriate method based on your needs: use temporary variables for testing and experimentation, user-specific files for personal customizations, and system-wide files for configurations that affect all users. Always follow security best practices, especially when dealing with sensitive information, and maintain proper documentation for custom variables in team environments.
By mastering environment variables, you'll have greater control over your Linux system and be better equipped to handle complex configuration requirements in both development and production environments.