BLOG POSTS
    MangoHost Blog / Export Command in Linux – How to Set Environment Variables
Export Command in Linux – How to Set Environment Variables

Export Command in Linux – How to Set Environment Variables

Environment variables are fundamental to Linux system operation and application configuration, allowing you to control program behavior, store sensitive data, and customize your shell environment. The export command is the primary tool for making these variables available to child processes and applications. Understanding how to properly set, manage, and troubleshoot environment variables is crucial for developers deploying applications, system administrators configuring servers, and anyone working with Linux systems. This guide covers everything from basic export syntax to advanced environment management techniques, common pitfalls, and real-world implementation scenarios.

How the Export Command Works

The export command in Linux promotes shell variables to environment variables, making them accessible to child processes. When you set a regular shell variable, it only exists within the current shell session. However, when you export a variable, it becomes part of the environment that gets passed down to any programs or scripts launched from that shell.

Here’s the technical distinction:

# Regular shell variable (only available in current shell)
MY_VAR="hello"

# Environment variable (available to child processes)
export MY_VAR="hello"

# Or combine declaration and export
export MY_VAR="hello"

When a process starts, it inherits a copy of its parent’s environment. Changes made to environment variables in child processes don’t affect the parent, creating isolated environments for each process tree.

Step-by-Step Implementation Guide

Basic Export Syntax

The export command has several syntax variations:

# Method 1: Declare then export
VARIABLE_NAME="value"
export VARIABLE_NAME

# Method 2: Export in one line
export VARIABLE_NAME="value"

# Method 3: Export multiple variables
export VAR1="value1" VAR2="value2" VAR3="value3"

# Method 4: Export without value (exports existing shell variable)
export VARIABLE_NAME

Setting Persistent Environment Variables

For variables that persist across sessions, you need to add them to shell configuration files:

# For current user only - add to ~/.bashrc or ~/.bash_profile
echo 'export NODE_ENV="production"' >> ~/.bashrc

# For all users - add to /etc/environment (Ubuntu/Debian)
echo 'JAVA_HOME="/usr/lib/jvm/java-11-openjdk-amd64"' | sudo tee -a /etc/environment

# For all users - add to /etc/profile
echo 'export LANG="en_US.UTF-8"' | sudo tee -a /etc/profile

Viewing and Managing Environment Variables

# Display all environment variables
env

# Display specific variable
echo $VARIABLE_NAME

# Display all exported variables in current shell
export -p

# Unset an environment variable
unset VARIABLE_NAME

Real-World Examples and Use Cases

Application Configuration

Modern applications often use environment variables for configuration, following 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 NODE_ENV="production"
export DEBUG="false"
export PORT="3000"

Development Environment Setup

Setting up 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 configurations
export EDITOR="vim"
export BROWSER="firefox"
export TERM="xterm-256color"

# Custom PATH additions
export PATH="$PATH:$HOME/bin:$GOPATH/bin:/usr/local/go/bin"

Docker and Container Environments

# Docker environment file (.env)
NODE_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

# Passing environment variables to Docker containers
docker run -e NODE_ENV=production -e PORT=3000 myapp:latest

Comparison with Alternative 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 Considerations

Security Best Practices

  • Never store sensitive data like passwords or API keys in global environment files
  • Use proper file permissions for files containing sensitive environment variables
  • Consider using secret management tools like HashiCorp Vault or AWS Secrets Manager
  • Regularly audit environment variables, especially in production systems
  • Use .env files for local development and proper secret injection for production
# 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

Naming Conventions

# Good practices for variable names
export API_BASE_URL="https://api.example.com"    # Clear, descriptive
export MAX_RETRY_ATTEMPTS="3"                    # Specific purpose
export FEATURE_FLAG_NEW_UI="true"               # Boolean flags

# Avoid these patterns
export x="value"                                  # Too generic
export MyVariable="value"                        # Mixed case
export api-url="https://api.example.com"        # Hyphens not recommended

Common Pitfalls and Troubleshooting

Variable Not Available in Child Process

This is the most common issue when variables aren’t properly exported:

# Wrong - variable not exported
DB_HOST="localhost"
./myapp  # Won't see DB_HOST

# Correct - variable exported
export DB_HOST="localhost"
./myapp  # Will see DB_HOST

Spaces and Special Characters

# Wrong - spaces break the assignment
export MESSAGE=Hello World

# Correct - quotes handle 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 Issues

Incorrectly modifying PATH can break system functionality:

# Wrong - overwrites existing PATH
export PATH="/usr/local/bin"

# Correct - appends to existing PATH
export PATH="$PATH:/usr/local/bin"

# Or prepend for priority
export PATH="/usr/local/bin:$PATH"

# Check PATH before and after changes
echo "Before: $PATH"
export PATH="$PATH:/new/path"
echo "After: $PATH"

Environment Variable Inheritance Issues

# Testing environment variable inheritance
export TEST_VAR="parent_value"

# Create test script to check 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 Environment Management Techniques

Conditional Environment Setup

# Environment-specific configuration
if [ "$NODE_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

Environment Variable Validation

# Function to validate required 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"

Dynamic Environment Loading

# Function to load .env files
load_env() {
    local env_file="${1:-.env}"
    
    if [ -f "$env_file" ]; then
        echo "Loading environment from $env_file"
        # Export variables from file, 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"

Integration with Modern Development Workflows

CI/CD Pipeline Integration

Environment variables are crucial in continuous integration and deployment:

# GitHub Actions example
name: Deploy Application
on: [push]
jobs:
  deploy:
    runs-on: ubuntu-latest
    env:
      NODE_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

# Kubernetes ConfigMap and Secret integration
apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
data:
  NODE_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 comprehensive information about environment variables and the export command, refer to the GNU Bash Manual’s Environment section and the POSIX standard for environment variables. These resources provide detailed specifications and additional advanced usage patterns for environment management in Unix-like systems.



This article incorporates information and material from various online sources. We acknowledge and appreciate the work of all original authors, publishers, and websites. While every effort has been made to appropriately credit the source material, any unintentional oversight or omission does not constitute a copyright infringement. All trademarks, logos, and images mentioned are the property of their respective owners. If you believe that any content used in this article infringes upon your copyright, please contact us immediately for review and prompt action.

This article is intended for informational and educational purposes only and does not infringe on the rights of the copyright owners. If any copyrighted material has been used without proper credit or in violation of copyright laws, it is unintentional and we will rectify it promptly upon notification. Please note that the republishing, redistribution, or reproduction of part or all of the contents in any form is prohibited without express written permission from the author and website owner. For permissions or further inquiries, please contact us.

Leave a reply

Your email address will not be published. Required fields are marked