Export Command in Linux – How to Set Environment Variables
Environment variables play a crucial role in the functioning of Linux systems and application settings. They let users modify the behaviour of programs, safeguard sensitive information, and tailor their shell environments. The export command serves as the main method for making these variables accessible to child processes and applications. Knowledge of how to effectively set, manage, and troubleshoot these variables is vital for developers, system administrators, and anyone interacting with Linux systems. This guide explores everything from the basics of export syntax to advanced management strategies, typical errors, and practical application scenarios.
Understanding the Export Command
The export command elevates shell variables to environment variables, enabling access for child processes. If you declare a standard shell variable, it remains confined to the current shell session. By exporting a variable, you ensure it becomes part of the broader environment, shared with any programs or scripts run from that shell.
Here’s how the distinction plays out:
# Standard shell variable (limited to current session)
MY_VAR="hello"
# Environment variable (accessible to child processes)
export MY_VAR="hello"
# Alternatively, declare and export simultaneously
export MY_VAR="hello"
When a process is initiated, it inherits a snapshot of its parent’s environment. Adjustments made to environment variables in any child process do not reverse effect on the parent, thereby creating distinct environments for each process hierarchy.
Step-by-Step Implementation Process
Basic Syntax for Export
The export command can be expressed through various syntax formats:
# Method 1: Declare and then export
VARIABLE_NAME="value"
export VARIABLE_NAME
# Method 2: One-line export
export VARIABLE_NAME="value"
# Method 3: Export multiple variables at once
export VAR1="value1" VAR2="value2" VAR3="value3"
# Method 4: Export an existing variable without a value
export VARIABLE_NAME
Creating Persistent Environment Variables
To maintain variables across sessions, they should be added to shell configuration files:
# User-specific - add to ~/.bashrc or ~/.bash_profile
echo 'export DE_ENV="production"' >> ~/.bashrc
# System-wide - add to /etc/environment (for Ubuntu/Debian)
echo 'JAVA_HOME="/usr/lib/jvm/java-11-openjdk-amd64"' | sudo tee -a /etc/environment
# System-wide - add to /etc/profile
echo 'export LANG="en_US.UTF-8"' | sudo tee -a /etc/profile
Managing and Viewing Environment Variables
# Display all environment variables
env
# Show a specific variable
echo $VARIABLE_NAME
# List all exported variables in the current shell
export -p
# Remove an environment variable
unset VARIABLE_NAME
Practical Examples and Scenarios
Configuration for Applications
Current applications commonly utilise environment variables for configuration, adhering to the twelve-factor app methodology:
# Database configuration
export DB_HOST="localhost"
export DB_PORT="5432"
export DB_NAME="myapp_production"
export DB_USER="appuser"
export DB_PASSWORD="secure_password"
# API keys and secrets
export STRIPE_API_KEY="sk_live_..."
export JWT_SECRET="your-256-bit-secret"
export REDIS_URL="redis://localhost:6379"
# Application settings
export DE_ENV="production"
export DEBUG="false"
export PORT="3000"
Setting Up a Development Environment
Configuring development tools and paths:
# Programming language environments
export JAVA_HOME="/usr/lib/jvm/java-11-openjdk-amd64"
export GOPATH="$HOME/go"
export GOROOT="/usr/local/go"
export PYTHON_PATH="/usr/local/lib/python3.9/site-packages"
# Tool settings
export EDITOR="vim"
export BROWSER="firefox"
export TERM="xterm-256color"
# Add custom paths
export PATH="$PATH:$HOME/bin:$GOPATH/bin:/usr/local/go/bin"
Docker and Containerised Environments
# Docker environment file (.env)
DE_ENV=production
DATABASE_URL=postgresql://user:pass@localhost:5432/db
REDIS_URL=redis://localhost:6379
API_BASE_URL=https://api.example.com
# Using with docker-compose
docker-compose --env-file .env up
# Providing environment variables to Docker containers
docker run -e DE_ENV=production -e PORT=3000 myapp:latest
Comparing Methods
Method | Scope | Persistence | Use Case | Performance |
---|---|---|---|---|
export command | Current session + child processes | Session only | Temporary settings, testing | Fast |
~/.bashrc | User sessions | Permanent for user | User-specific configuration | Loaded per session |
/etc/environment | System-wide | Permanent | System configuration | Loaded at login |
systemd service files | Specific service | Service lifetime | Application deployment | Service-isolated |
env command | Single command execution | Command duration | One-off executions | Minimal overhead |
Best Practices and Security Tips
Security Best Practices
- Avoid storing sensitive details like passwords or API keys in global environment files
- Ensure proper file permissions for files holding sensitive environment variables
- Consider using secret management tools such as HashiCorp Vault or AWS Secrets Manager
- Regularly review environment variables, particularly in production environments
- Utilize .env files for local development and appropriate secret injection for production environments
# Secure .env file permissions
chmod 600 .env
chown appuser:appuser .env
# Example of secure environment variable injection
# Using systemd service file
[Service]
Environment="DB_PASSWORD_FILE=/run/secrets/db_password"
EnvironmentFile=/etc/myapp/config
Convention for Naming Variables
# Recommendations for variable names
export API_BASE_URL="https://api.example.com" # Clear, descriptive names
export MAX_RETRY_ATTEMPTS="3" # Specific purpose
export FEATURE_FLAG_NEW_UI="true" # Boolean flags
# Patterns to avoid
export x="value" # Too vague
export MyVariable="value" # Mixed case
export api-url="https://api.example.com" # Hyphens are not recommended
Common Challenges and Troubleshooting Tips
Variable Not Available in Child Processes
This is a frequent issue when variables aren’t correctly exported:
# Incorrect - variable not exported
DB_HOST="localhost"
./myapp # Won't recognise DB_HOST
# Correct - variable exported
export DB_HOST="localhost"
./myapp # Will recognise DB_HOST
Spaces and Special Characters
# Incorrect - spaces disrupt assignment
export MESSAGE=Hello World
# Correct - encapsulate with quotes to allow spaces
export MESSAGE="Hello World"
# Handling special characters
export SPECIAL_CHARS='Password with $pecial @nd "quotes"'
export JSON_CONFIG='{"host": "localhost", "port": 3000}'
PATH Variable Problems
Incorrect adjustments to PATH can compromise system performance:
# Incorrect - overwrites current PATH
export PATH="/usr/local/bin"
# Correct - appends to the existing PATH
export PATH="$PATH:/usr/local/bin"
# Or prepend for priority
export PATH="/usr/local/bin:$PATH"
# Check PATH before and after adjustments
echo "Before: $PATH"
export PATH="$PATH:/new/path"
echo "After: $PATH"
Issues with Environment Variable Inheritance
# Examining environment variable inheritance
export TEST_VAR="parent_value"
# Create testing script to assess inheritance
cat << 'EOF' > test_env.sh
#!/bin/bash
echo "TEST_VAR in child: $TEST_VAR"
EOF
chmod +x test_env.sh
./test_env.sh # Should output: TEST_VAR in child: parent_value
Advanced Management of Environment Variables
Conditional Environment Setup
# Configuration based on environment
if [ "$DE_ENV" = "production" ]; then
export LOG_LEVEL="error"
export DEBUG="false"
export CACHE_TTL="3600"
else
export LOG_LEVEL="debug"
export DEBUG="true"
export CACHE_TTL="60"
fi
# Host-specific configuration
HOSTNAME=$(hostname)
case $HOSTNAME in
web-server-*)
export SERVER_ROLE="web"
export WORKER_PROCESSES="4"
;;
db-server-*)
export SERVER_ROLE="database"
export MAX_CONNECTIONS="1000"
;;
esac
Validating Environment Variables
# Function to check for necessary environment variables
check_required_vars() {
local missing_vars=""
for var in "$@"; do
if [ -z "${!var}" ]; then
missing_vars="$missing_vars $var"
fi
done
if [ -n "$missing_vars" ]; then
echo "Error: Missing required environment variables:$missing_vars"
exit 1
fi
}
# Usage
check_required_vars "DATABASE_URL" "API_KEY" "SECRET_KEY"
Loading Environment Variables Dynamically
# Function to read .env files
load_env() {
local env_file="${1:-.env}"
if [ -f "$env_file" ]; then
echo "Loading environment from $env_file"
# Export variables from the file, while handling comments and empty lines
export $(grep -v '^#' "$env_file" | grep -v '^$' | xargs)
else
echo "Warning: $env_file not found"
fi
}
# Usage
load_env ".env.production"
Integrating with Current Development Workflows
CI/CD Pipeline Integration
Environment variables are integral to continuous integration and deployment:
# Example for GitHub Actions
name: Deploy Application
on: [push]
jobs:
deploy:
runs-on: ubuntu-latest
env:
DE_ENV: production
API_BASE_URL: ${{ secrets.API_BASE_URL }}
steps:
- name: Deploy with environment
run: |
export BUILD_NUMBER="${{ github.run_number }}"
export COMMIT_SHA="${{ github.sha }}"
./deploy.sh
Kubernetes Integration
# Integration with ConfigMap and Secret in Kubernetes
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
data:
DE_ENV: "production"
LOG_LEVEL: "info"
---
apiVersion: apps/v1
kind: Deployment
spec:
template:
spec:
containers:
- name: app
envFrom:
- configMapRef:
name: app-config
env:
- name: DATABASE_PASSWORD
valueFrom:
secretKeyRef:
name: db-secret
key: password
For in-depth details regarding environment variables and the export command, consult the GNU Bash Manual’s Environment section and the POSIX standard for environment variables. These sources offer comprehensive specifications and additional advanced usage patterns for managing the environment in Unix-like systems.
This article includes information and insights from various online sources. We acknowledge and appreciate the contributions of all original authors, publishers, and websites. While every effort has been made to credit source material accurately, any unintentional oversight does not constitute a copyright infringement. All trademarks, logos, and images belong to their respective owners. If you believe any content used in this article infringes your copyright, please get in touch with us promptly for review and action.
This content is meant solely for informational and educational purposes and does not infringe on the rights of copyright holders. Should any copyrighted materials have been used without proper attribution or in violation of copyright laws, it is unintended, and we will make necessary corrections immediately upon notification. Please note that the republishing, redistribution, or reproduction of any part of this article in any format is prohibited without the express written consent of the author and website owner. For permissions or further inquiries, please contact us.